react#ChangeEventHandler TypeScript Examples

The following examples show how to use react#ChangeEventHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ChangeLanguage.tsx    From yasd with MIT License 6 votes vote down vote up
ChangeLanguage = (): JSX.Element => {
  const { i18n } = useTranslation()
  const options = [
    {
      value: 'en',
      label: 'English',
    },
    {
      value: 'zh',
      label: '中文',
    },
  ]
  const [isLoading, setIsLoading] = useState(false)

  const onChange: ChangeEventHandler<HTMLSelectElement> = useCallback(
    (e) => {
      setIsLoading(true)
      store.set(LastUsedLanguage, e.target.value)
      i18n.changeLanguage(e.target.value).finally(() => setIsLoading(false))
    },
    [i18n],
  )

  return (
    <div tw="flex justify-center w-full">
      <Select
        label="change language"
        hideLabel
        noMargin
        value={i18n.language}
        options={options}
        onChange={onChange}
        disabled={isLoading}
      />
    </div>
  )
}
Example #2
Source File: AddressInput.tsx    From mStable-apps with GNU Lesser General Public License v3.0 6 votes vote down vote up
AddressInput: FC<Props> = ({ onClick, title, className }) => {
  const inputValue = useRef<string | undefined>()
  const [invalid, setInvalid] = useState(false)

  const handleChange = useCallback<ChangeEventHandler<HTMLInputElement>>(event => {
    inputValue.current = event.target.value
  }, [])

  const handleClick = useCallback(() => {
    const address = inputValue.current ?? ''
    if (!isAddress(address)) {
      setInvalid(true)
      setTimeout(() => setInvalid(false), 200)
      return
    }
    onClick(address)
  }, [onClick])

  return (
    <Container className={className}>
      <CSSTransition in={invalid} timeout={200}>
        {className => <StyledInput className={className} placeholder="0x0000…0000" onChange={handleChange} />}
      </CSSTransition>
      <Button onClick={handleClick}>{title}</Button>
    </Container>
  )
}
Example #3
Source File: AmountInput.tsx    From mStable-apps with GNU Lesser General Public License v3.0 6 votes vote down vote up
AmountInput: FC<Props> = ({
  className,
  error,
  disabled = false,
  placeholder = '0.0',
  onChange,
  value,
  min = '0',
  max,
  step = '0.01',
  decimals,
}) => {
  const trimmedValue = useMemo(() => trimInput(value, decimals), [value, decimals])

  const handleKeyPress = useCallback<KeyboardEventHandler<HTMLInputElement>>(event => {
    // Prevent 'minus' key
    if ((event.which || event.keyCode) === 45) {
      event.preventDefault()
      event.stopPropagation()
    }
  }, [])

  const handleChange = useCallback<ChangeEventHandler<HTMLInputElement>>(event => onChange?.(event.target.value ?? undefined), [onChange])

  return (
    <Input
      className={className}
      error={error}
      min={min}
      max={max}
      placeholder={placeholder}
      step={step}
      value={trimmedValue}
      onKeyPress={handleKeyPress}
      onChange={handleChange}
      disabled={disabled}
    />
  )
}
Example #4
Source File: AmountInputButton.tsx    From mStable-apps with GNU Lesser General Public License v3.0 6 votes vote down vote up
AmountInputButton: FC<Props> = ({ className, disabled = false, placeholder = '0.00', onChange, value, min = '0', max }) => {
  const handleKeyPress = useCallback<KeyboardEventHandler<HTMLInputElement>>(event => {
    // Prevent 'minus' key
    if ((event.which || event.keyCode) === 45) {
      event.preventDefault()
      event.stopPropagation()
    }
  }, [])

  const handleChange = useCallback<ChangeEventHandler<HTMLInputElement>>(
    event => {
      onChange?.(event.target.value ?? undefined)
    },
    [onChange],
  )

  return (
    <StyledButton className={className}>
      <input
        type="number"
        min={min}
        max={max}
        placeholder={placeholder}
        step="0.01"
        value={value || ''}
        onKeyPress={handleKeyPress}
        onChange={handleChange}
        disabled={disabled}
      />
    </StyledButton>
  )
}
Example #5
Source File: Search.tsx    From minesweeper with MIT License 6 votes vote down vote up
Search: FC = () => {
  const [search, setSearch] = useState<string>('');

  const onChange: ChangeEventHandler<HTMLInputElement> = ({ target }) => {
    setSearch(target.value);
  };

  return (
    <div>
      <SearchInput search={search} onChange={onChange} />
      <p>Searches for {search ? search : '...'}</p>
    </div>
  );
}
Example #6
Source File: Attachment.tsx    From advocacy-maps with MIT License 5 votes vote down vote up
export function Attachment({
  attachment
}: {
  attachment: UseDraftTestimonyAttachment
}) {
  const { upload, error, id } = attachment
  const [key, setKey] = useState(0),
    clearInput = useCallback(() => setKey(s => s + 1), [])
  const onFileSelected: ChangeEventHandler<HTMLInputElement> = useCallback(
    e => {
      const files = e.target.files
      if (files?.length) {
        const file = files[0]
        upload(file)
      }
    },
    [upload]
  )

  useEffect(() => {
    if (error) clearInput()
  }, [clearInput, error])

  return (
    <Form.Group controlId="testimonyAttachment">
      <Label attachment={attachment} />
      {id ? (
        <Attached attachment={attachment} />
      ) : (
        <InputGroup>
          <Form.Control
            key={key}
            type="file"
            accept="application/pdf"
            onChange={onFileSelected}
          />
        </InputGroup>
      )}
      <StatusMessage attachment={attachment} />
    </Form.Group>
  )
}
Example #7
Source File: CapabilityTile.tsx    From yasd with MIT License 5 votes vote down vote up
CapabilityTile: React.FC<CapabilityTileProps> = ({
  api,
  title,
  link,
}) => {
  const { t } = useTranslation()
  const profile = useProfile()
  const { data: capability } = useSWR<Capability>(
    profile !== undefined ? api : null,
    fetcher,
  )
  const history = useHistory()

  const toggle: ChangeEventHandler<HTMLButtonElement> = useCallback(
    (e) => {
      e.stopPropagation()
      e.preventDefault()

      fetcher({
        method: 'POST',
        url: api,
        data: {
          enabled: !capability?.enabled,
        },
      })
        .then(() => {
          return mutate(api)
        })
        .catch((err) => {
          console.error(err)
        })
    },
    [api, capability],
  )

  return (
    <MenuTile onClick={link ? () => history.push(link) : undefined}>
      <MenuTileTitle title={t(`home.${title}`)} />

      <MenuTileContent css={[tw`flex justify-end`]}>
        <Toggle
          noMargin
          label=""
          labelChecked={t('common.on')}
          labelUnchecked={t('common.off')}
          checked={capability?.enabled}
          onChange={toggle}
        />
      </MenuTileContent>
    </MenuTile>
  )
}
Example #8
Source File: SendAsset.tsx    From mStable-apps with GNU Lesser General Public License v3.0 5 votes vote down vote up
SendAsset: FC<Props> = ({ symbol }) => {
  const tokenState = useTokensState()
  const propose = usePropose()
  const signer = useSigner()
  const inputAddress = useRef<string | undefined>()

  const tokenAddress = useMemo(
    () => Object.keys(tokenState.tokens).find(address => tokenState.tokens[address]?.symbol === symbol),
    [tokenState, symbol],
  )

  const token = tokenState.tokens[tokenAddress ?? '']

  const [inputAmount, inputFormValue, setInputFormValue] = useBigDecimalInput('0', token?.decimals)

  const handleAddressChange = useCallback<ChangeEventHandler<HTMLInputElement>>(event => {
    inputAddress.current = event.target.value ?? undefined
  }, [])

  const handleAmountChange = useCallback<ChangeEventHandler<HTMLInputElement>>(
    event => {
      setInputFormValue(event.target.value ?? undefined)
    },
    [setInputFormValue],
  )

  const handleSend = (): void => {
    if (!tokenAddress || !signer || !inputAddress.current || !inputAmount) return
    return propose<Interfaces.ERC20, 'transfer'>(
      new TransactionManifest(ERC20__factory.connect(tokenAddress, signer), 'transfer', [inputAddress.current, inputAmount.exact], {
        present: `Transfer ${symbol ? ` ${inputAmount.simple} ${symbol} to ${inputAddress.current}` : ''}`,
        past: `Transfer${symbol ? ` ${inputAmount.simple} ${symbol} to ${inputAddress.current}` : ''}`,
      }),
    )
  }

  return (
    <Container>
      <div>
        <Input placeholder="0.00" value={inputFormValue} onChange={handleAmountChange} />
        <span>to</span>
        <Input placeholder="0x000…" onChange={handleAddressChange} />
        <Button onClick={handleSend}>Send</Button>
      </div>
    </Container>
  )
}
Example #9
Source File: GasStation.tsx    From mStable-apps with GNU Lesser General Public License v3.0 5 votes vote down vote up
GasStation: FC = () => {
  const networkPrices = useNetworkPrices()
  const { gasLimit, gasPrice, setGasPrice } = useGas()

  const [gasPriceType, setGasPriceType] = useState<GasPriceType>(GasPriceType.Standard)

  const customTransactionFee =
    gasPriceType === GasPriceType.Custom && gasPrice && networkPrices.value?.nativeToken && gasLimit
      ? (gasPrice / 1e9) * (networkPrices.value.nativeToken / 1e9) * gasLimit.toNumber()
      : undefined

  const handleChange = useCallback<ChangeEventHandler<HTMLInputElement>>(
    event => {
      setGasPrice(parseFloat(event.target.value) * 1e9)
    },
    [setGasPrice],
  )

  useEffectOnce(() => {
    setGasPrice((networkPrices.value?.gas?.[gasPriceType as 'fast'] ?? 0) * 1e9)
  })

  return (
    <Container>
      {OPTIONS.map(({ type, label }) => {
        const _gasPrice = networkPrices.value?.gas?.[type as 'fast']

        const transactionFee =
          _gasPrice && networkPrices.value?.nativeToken && gasLimit
            ? _gasPrice * (networkPrices.value?.nativeToken / 1e9) * gasLimit.toNumber()
            : undefined

        const selected = type === gasPriceType
        return (
          <Option key={type}>
            <OptionButton
              highlighted={selected}
              onClick={() => {
                setGasPrice((_gasPrice as number) * 1e9)
                setGasPriceType(type)
              }}
            >
              {label}
            </OptionButton>
            <div>
              {type === GasPriceType.Custom ? (
                <div>
                  <Input disabled={type !== gasPriceType} placeholder="10" onChange={handleChange} />
                  <Fee>{customTransactionFee ? `$${customTransactionFee.toFixed(2)}` : '$–'}</Fee>
                </div>
              ) : (
                <div>
                  <Price>{_gasPrice?.toFixed(0)}</Price>
                  <Fee>{transactionFee ? `$${transactionFee.toFixed(2)}` : '–'}</Fee>
                </div>
              )}
            </div>
          </Option>
        )
      })}
    </Container>
  )
}
Example #10
Source File: Language.tsx    From GTAV-NativeDB with MIT License 4 votes vote down vote up
export function CodeGenOptionComponent<TSettings>(props:CodeGenOptionComponentProps<TSettings>) {
  const { type, label, prop, value, onChange } = props

  switch (type) {
    case 'boolean':
      return (
        <FormControlLabel
          control={
            <Checkbox
              name={prop}
              checked={value}
              onChange={onChange}
            />
          }
          sx={{ userSelect: 'none' }}
          label={label}
        />
      )
    case 'combo':
      const options = props.options
      return (
        <FormControl fullWidth>
          <InputLabel id={`${prop}-label`}>{label}</InputLabel>
          <Select
            id={`${prop}-select`}
            labelId={`${prop}-label`}
            name={prop}
            value={value}
            onChange={onChange}
            label={label}
          >
            {options.map(({ label, value }) => (
              <MenuItem key={value} value={value}>
                {label}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
      )
    case 'string':
      return (
        <TextField
          label={label}
          name={prop}
          onChange={(onChange as unknown as ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement>)}
          value={value}
        />
      )
  }
}
Example #11
Source File: index.tsx    From xiaobi with MIT License 4 votes vote down vote up
Index: React.FC<Props> = ({ match }) => {
	const id = match.params.id.split('?')[0];
	const pair = getLocationQuery(window.location.href, 'pair');
	const history = useHistory();
	const [keywords, setKeyWords] = useState<string>();
	const [enable, setEnable] = useState(false);
	const [isFocus, setFocus] = useState(false);
	const [times, setTimes] = useState(0);
	const inputEl = useRef<HTMLInputElement>(null);
	const { data } = useLoop({
		fn: () => sendMessage({ command: CMDS.CMD_NOTICEINFO, data: id }),
		updated: [times],
		delay: 3000,
	});

	const handleCreate = useMemo(
		() =>
			debounce(() => {
				if (!enable || !keywords) return;

				const time = Date.now();
				const params: NoticeType = {
					id,
					uid: `${id}_${time}`,
					name: data.pair,
					type: 'price',
					rule: Number(keywords).toString(),
					market: data.market,
					create: time,
					compare: Number(keywords) > data.usd,
				};

				sendMessage({ command: CMDS.CMD_ADDNOTICE, data: params })
					.then((isSend) => {
						setTimes(times + 1);
						setEnable(false);
						if (inputEl.current) {
							inputEl.current.value = '';
						}

						message.info('通知创建成功');
					})
					.catch((error) => error);
			}, 500),
		[enable, keywords],
	);

	const goBack = () => history.replace({ pathname: StaticRoutes.Notify });
	const handleFocus = () => setFocus(true);
	const handleBlur = () => setFocus(false);
	const handleKeyup: KeyboardEventHandler<HTMLInputElement> = (e) => {
		if (e.key == 'Enter') {
			handleCreate();
		}
	};
	const handleChange: ChangeEventHandler<HTMLInputElement> = (e) => {
		setEnable(!!e.target.value);
		setKeyWords(e.target.value);
	};

	const handleDel = (uid: string) => {
		sendMessage({ command: CMDS.CMD_DELNOTICE, data: uid });
		setTimes(times + 1);
	};

	const renderDataJSX = () => {
		if (data?.pair) {
			const { usd, cny, percent } = data;
			const className = percent > 0 ? 'increase' : 'decrease';
			const p = percent > 0 ? `+${percent}%` : `${percent}%`;

			return (
				<DataUI>
					<p className='usd'>{usd}</p>
					<div className='desc'>
						<p>¥{cny}</p>
						<p className={className}>{p}</p>
					</div>
				</DataUI>
			);
		}

		return (
			<DataUI>
				<DataLoading />
			</DataUI>
		);
	};
	const renderListJSX = () => {
		if (data?.list.length) {
			return (data.list as NoticeType[]).map((v) => (
				<ListBlock {...v} key={v.uid} current={data.usd} delEvent={() => handleDel(v.uid)} />
			));
		}
		return <Empty />;
	};

	return (
		<WrapperUI>
			<ContentUI>
				<HeadUI>
					<p className='name'>{pair}</p>
					<p className='back' onClick={goBack}>
						返回
					</p>
				</HeadUI>
				{renderDataJSX()}
				<InputBoxUI className={`${isFocus ? 'active' : ''}`}>
					<input
						ref={inputEl}
						type='number'
						placeholder='请输入价格'
						onFocus={handleFocus}
						onBlur={handleBlur}
						onKeyDown={handleKeydown}
						onKeyUp={handleKeyup}
						onChange={handleChange}
					/>
				</InputBoxUI>
				<BtnUI className={`${enable ? 'active' : ''}`} onClick={handleCreate}>
					创建提醒
				</BtnUI>
				<DescUI>提示:插件通知需开启浏览器通知权限,插件会定时更新数据根据填入规则决定是否通知</DescUI>
			</ContentUI>
			<ListUI>
				<TabUI>
					<p>类型</p>
					<p>提醒规则</p>
					<p>操作</p>
				</TabUI>
				<ScrollUI>{renderListJSX()}</ScrollUI>
			</ListUI>
		</WrapperUI>
	);
}