react#FormEvent TypeScript Examples

The following examples show how to use react#FormEvent. 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: PlaygroundNftExtrinsics.tsx    From atlas with GNU General Public License v3.0 6 votes vote down vote up
CancelSale: React.FC<FormProps> = ({ videoId, onSuccess, onError, type }) => {
  const { joystream, proxyCallback } = useJoystream()
  const handleTransaction = useTransaction()
  const { activeMemberId } = useAuthorizedUser()

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault()
    if (!joystream || !type) return

    handleTransaction({
      onError,
      txFactory: async (updateStatus) =>
        (await joystream.extrinsics).cancelNftSale(videoId, activeMemberId, type, proxyCallback(updateStatus)),
      onTxSync: async (_) => onSuccess(),
    })
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <Button type="submit">Cancel sale</Button>
      </form>
    </div>
  )
}
Example #2
Source File: Login.tsx    From avalon.ist with MIT License 6 votes vote down vote up
handleSubmit = (event: FormEvent) => {
    event.preventDefault();

    this.setState({ error: null });
    
    login(this.state.username, this.state.password, (err) =>
      this.setState({ error: err })
    );
  };
Example #3
Source File: NewArticle.tsx    From ts-redux-react-realworld-example-app with MIT License 6 votes vote down vote up
async function onSubmit(ev: FormEvent) {
  ev.preventDefault();
  store.dispatch(startSubmitting());
  const result = await createArticle(store.getState().editor.article);

  result.match({
    err: (errors) => store.dispatch(updateErrors(errors)),
    ok: ({ slug }) => {
      location.hash = `#/article/${slug}`;
    },
  });
}
Example #4
Source File: index.ts    From webapis-playground with MIT License 6 votes vote down vote up
async function onCopy(event: FormEvent<HTMLButtonElement>) {
  event.preventDefault();

  const input = document.getElementById('js-input--copy') as HTMLInputElement;

  try {
    let value = input.value;

    if (hasSupport()) {
      await navigator.clipboard.writeText(value);
      console.log(`The text '${value}' is in the Clipboard Now!`);
    } else {
      console.log(`Clipboard API is Not Supported`);
    }
  } catch (err) {
    console.error(`Failed to copy: ${err}`);
  }
}
Example #5
Source File: PriceModal.tsx    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
function PriceModal({ heading, close, onSubmit }: Props) {
  const { value: price, handleChange: handlePriceChange } = useInput('');

  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (Number(price) > 0) onSubmit(price);
  };

  return (
    <Modal heading={heading} close={close}>
      <form className={styles.form} onSubmit={handleSubmit}>
        <Input value={price} onChange={handlePriceChange} />
        <Button type="submit" text="OK" block />
      </form>
    </Modal>
  );
}
Example #6
Source File: SettingsUtils.tsx    From flood with GNU General Public License v3.0 6 votes vote down vote up
handleClientSettingChange = (event: FormEvent<HTMLFormElement> | Event): Partial<ClientSettings> => {
  const inputElement = event.target as HTMLInputElement;
  const property = inputElement.name as ClientSetting;
  const {value, type, checked} = inputElement;

  let changedClientSetting: Partial<ClientSettings> = {};
  if (type === 'checkbox') {
    changedClientSetting = {[property]: checked};
  } else {
    changedClientSetting = {[property]: value};
  }

  return changedClientSetting;
}
Example #7
Source File: Chat.tsx    From react-js-tutorial with MIT License 6 votes vote down vote up
onSubmit = (event: FormEvent): void => {
    event.preventDefault();
    const { message } = this.state;
    const { username, send } = this.props;
    if (!isEmpty(message)) {
      send({ message, author: username });
      this.setState({ message: "" });
    }
  };
Example #8
Source File: Flow.tsx    From kratos-selfservice-ui-react-nextjs with Apache License 2.0 6 votes vote down vote up
// Handles form submission
  handleSubmit = (e: MouseEvent | FormEvent) => {
    // Prevent all native handlers
    e.stopPropagation()
    e.preventDefault()

    // Prevent double submission!
    if (this.state.isLoading) {
      return Promise.resolve()
    }

    this.setState((state) => ({
      ...state,
      isLoading: true
    }))

    return this.props.onSubmit(this.state.values).finally(() => {
      // We wait for reconciliation and update the state after 50ms
      // Done submitting - update loading status
      this.setState((state) => ({
        ...state,
        isLoading: false
      }))
    })
  }
Example #9
Source File: Input.tsx    From website-docs with MIT License 6 votes vote down vote up
export function SearchInput({
  docInfo: { type, version },
  searchValue,
  setSearchValue,
}: Props) {
  const { t, navigate } = useI18next()

  const handleSearchInputKeyDown = useCallback(
    (e: FormEvent) => {
      e.preventDefault()

      navigate(`/search?type=${type}&version=${version}&q=${searchValue}`, {
        state: {
          type,
          version,
          query: searchValue,
        },
      })
    },
    [type, version, searchValue]
  )

  return (
    <Field as="form" onSubmit={handleSearchInputKeyDown}>
      <Control hasIcons="left">
        <BulmaInput
          type="search"
          placeholder={t('navbar.searchDocs')}
          value={searchValue}
          onChange={e => setSearchValue(e.target.value)}
        />
        <span className="icon is-left">
          <MdSearch />
        </span>
      </Control>
    </Field>
  )
}
Example #10
Source File: PageHeader.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
SelectNav = ({ main, customCss }: { main: NavModelItem; customCss: string }) => {
  const defaultSelectedItem = main.children.find(navItem => {
    return navItem.active === true;
  });

  const gotoUrl = (evt: FormEvent) => {
    const element = evt.target as HTMLSelectElement;
    const url = element.options[element.selectedIndex].value;
    appEvents.emit(CoreEvents.locationChange, { href: url });
  };

  return (
    <div className={`gf-form-select-wrapper width-20 ${customCss}`}>
      <label className={`gf-form-select-icon ${defaultSelectedItem.icon}`} htmlFor="page-header-select-nav" />
      {/* Label to make it clickable */}
      <select
        className="gf-select-nav gf-form-input"
        value={defaultSelectedItem.url}
        onChange={gotoUrl}
        id="page-header-select-nav"
      >
        {main.children.map((navItem: NavModelItem) => {
          if (navItem.hideFromTabs) {
            // TODO: Rename hideFromTabs => hideFromNav
            return null;
          }
          return (
            <option key={navItem.url} value={navItem.url}>
              {navItem.text}
            </option>
          );
        })}
      </select>
    </div>
  );
}
Example #11
Source File: AppListCard.tsx    From one-platform with MIT License 5 votes vote down vote up
AppListCard = ({ apps, onSubmit, filteredApps }: Props): JSX.Element => {
  const [selectedApps, setSelectedApps] = useState(filteredApps);

  const onAppCheckboxChange = useCallback(
    (app: App) => {
      const appsSelected = { ...selectedApps };
      if (appsSelected?.[app.id]) {
        delete appsSelected[app.id];
      } else {
        appsSelected[app.id] = app;
      }
      setSelectedApps(appsSelected);
    },
    [selectedApps]
  );

  const onApplyFilter = (event: FormEvent<HTMLFormElement>): void => {
    event.preventDefault();
    if (onSubmit && selectedApps) onSubmit(selectedApps);
  };

  return (
    <form onSubmit={onApplyFilter}>
      <Grid hasGutter>
        {apps?.map((app, index) => (
          <GridItem key={app.id} span={4}>
            <Checkbox
              id={`${app.id}-${index}`}
              name={`${app.id}-${index}`}
              style={{ whiteSpace: 'nowrap' }}
              label={app.name}
              isChecked={Boolean(selectedApps?.[app.id])}
              onChange={() => onAppCheckboxChange(app)}
              className="capitalize"
            />
          </GridItem>
        ))}
        <GridItem span={12}>
          <Button type="submit">Apply</Button>
        </GridItem>
      </Grid>
    </form>
  );
}
Example #12
Source File: ChannelSearch.tsx    From atlas with GNU General Public License v3.0 5 votes vote down vote up
ChannelSearch: React.FC<SearchProps> = ({
  isSearchInputOpen,
  setIsSearching,
  isSearching,
  submitSearch,
  setIsSearchingInputOpen,
  setSearchQuery,
  searchQuery,
}) => {
  const searchInputRef = useRef<HTMLInputElement>(null)

  const handleEscape = useCallback(
    (event: React.KeyboardEvent<HTMLInputElement>) => {
      if (event.key === 'Escape' || event.key === 'Esc') {
        setIsSearchingInputOpen(false)
        event.currentTarget.blur()
        setSearchQuery('')
      }
    },
    [setIsSearchingInputOpen, setSearchQuery]
  )

  const toggleSearchInput = useCallback(() => {
    if (isSearchInputOpen) {
      setIsSearchingInputOpen(false)
      searchInputRef.current?.blur()
    } else {
      setIsSearchingInputOpen(true)
      searchInputRef.current?.focus()
    }
  }, [isSearchInputOpen, searchInputRef, setIsSearchingInputOpen])

  useEffect(() => {
    const onClickOutsideSearch = (event: Event) => {
      if (!isSearching && isSearchInputOpen && searchInputRef.current !== event.target) {
        toggleSearchInput()
      }
    }
    window.addEventListener('click', onClickOutsideSearch)
    return () => {
      window.removeEventListener('click', onClickOutsideSearch)
    }
  }, [isSearching, isSearchInputOpen, searchInputRef, searchQuery, setIsSearchingInputOpen, toggleSearchInput])

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault()
    if (searchQuery.trim() === '') {
      setIsSearching(false)
    } else {
      submitSearch(searchQuery)
      setIsSearching(true)
    }
  }

  return (
    <SearchContainerForm onSubmit={handleSubmit}>
      <StyledTextField
        ref={searchInputRef}
        isOpen={isSearchInputOpen}
        isSearching={isSearching}
        value={searchQuery}
        onChange={(e) => setSearchQuery(e.target.value)}
        onKeyDown={handleEscape}
        placeholder="Search"
        type="search"
      />
      <SearchButton onClick={toggleSearchInput} variant="tertiary">
        <SvgActionSearch />
      </SearchButton>
    </SearchContainerForm>
  )
}
Example #13
Source File: index.tsx    From gonear-name with The Unlicense 5 votes vote down vote up
Offer = () => {
  const [offer, setOffer] = useState('')
  const [beneficiar, setBeneficiar] = useState('')
  const form = useRef<HTMLFormElement | null>()
  const beneficiarInput = useRef<HTMLInputElement | null>()


  const { near }: { near: INearProps | null } = useContext(NearContext)

  const submitForm = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault()

    if (!near || !form?.current) return
    if (!form.current.reportValidity()) return

    if (offer === beneficiar) {
      alert('Accounts must be different')
      return
    }

    const balance = await near.api.get_balance(offerAccountId)
    if (!balance) {
      alert('Account not exist - you have to create it first')
      return
    }
    if (balance < 2.03) {
      alert('Not enough balance - should be at least 2 NEAR available (2.05 total usually works)')
      return
    }

    await near.api.addFullAccessKey({
      account_id: offerAccountId,
      successUrl: window.location.origin + `/#/offer-processing/${offerAccountId}/${beneficiarAccountId}`,
      failureUrl: window.location.origin + '/#/offer-failure/'
    })
  }
  useTopScroll()

  if (!near) return null
  const suffix = near.config.accountSuffix
  const offerAccountId = offer + '.' + suffix
  const beneficiarAccountId = beneficiar + '.' + suffix

  return (
    <Container>
      <Main>
        <Title>Offer your <br /> account</Title>
        <DetailsOne>Here you can offer your account to the Market. Choose an account to transfer all rewards after claiming your account.</DetailsOne>
        <DetailsTwo>This is NEAR Account Marketplace. It allows you to sell, bid and buy NEAR Account names.</DetailsTwo>
      </Main>
      <Form ref={form} onSubmit={submitForm}>
        <HeadOne>Account you offer</HeadOne>
        <InputContainer>
          <Input value={offer} onChange={(e: any) => setOffer(e.target.value)} required maxLength={63} pattern={`.*(?<!\\.${suffix})$`} />
          <InputSuffix>.{suffix}</InputSuffix>
        </InputContainer>
        <Helper>All your access keys will be removed</Helper>
        <HeadTwo>Account which takes rewards</HeadTwo>
        <InputContainer>
          <Input value={beneficiar} ref={beneficiarInput} onChange={(e: any) => setBeneficiar(e.target.value)} required maxLength={63} pattern={`.*(?<!\\.${suffix})$`} />
          <InputSuffix>.{suffix}</InputSuffix>
        </InputContainer>
        <Helper>All rewards will be transferred to this account</Helper>
        <Button type="submit">Offer {offer?.length ? offerAccountId : ''}</Button>
      </Form>
    </Container>
  )
}
Example #14
Source File: index.tsx    From pola-web with MIT License 5 votes vote down vote up
handleClickOutside = (evt: FormEvent) => {
    this.props.clickOutsideHandler && this.props.clickOutsideHandler();
  };
Example #15
Source File: Chat.tsx    From avalon.ist with MIT License 5 votes vote down vote up
handleSubmit = (event: FormEvent) => {
    event.preventDefault();

    this.sendMessage();
  };
Example #16
Source File: Model.ts    From hive with MIT License 5 votes vote down vote up
@action.bound
    selectSensor(event: FormEvent<HTMLInputElement>) {
        this.selectedSensorId = event.currentTarget.value as SensorIds;
    }
Example #17
Source File: SaveToDashboardModal.tsx    From posthog-foss with MIT License 5 votes vote down vote up
export function SaveToDashboardModal({ visible, closeModal, insight }: SaveToDashboardModalProps): JSX.Element {
    const logic = saveToDashboardModalLogic({ id: insight.short_id, fromDashboard: insight.dashboard || undefined })
    const { nameSortedDashboards } = useValues(dashboardsModel)
    const { dashboardId } = useValues(logic)
    const { addNewDashboard, setDashboardId } = useActions(logic)
    const { reportSavedInsightToDashboard } = useActions(eventUsageLogic)
    const { insightLoading } = useValues(insightLogic)
    const { updateInsight } = useActions(insightLogic)

    async function save(event: MouseEvent | FormEvent): Promise<void> {
        event.preventDefault()
        updateInsight({ ...insight, dashboard: dashboardId }, () => {
            reportSavedInsightToDashboard()
            toast(
                <div data-attr="success-toast">
                    Panel added to dashboard.&nbsp;
                    <Link to={`/dashboard/${dashboardId}`}>Click here to see it.</Link>
                </div>
            )
            closeModal()
        })
    }

    return (
        <Modal
            onOk={(e) => void save(e)}
            onCancel={closeModal}
            afterClose={closeModal}
            confirmLoading={insightLoading}
            visible={visible}
            title="Add to dashboard"
            okText="Add insight to dashboard"
        >
            <form onSubmit={(e) => void save(e)}>
                <label>Dashboard</label>
                <Select
                    value={dashboardId}
                    onChange={(id) => (id === 'new' ? addNewDashboard() : setDashboardId(id))}
                    style={{ width: '100%' }}
                >
                    {nameSortedDashboards.map((dashboard) => (
                        <Select.Option key={dashboard.id} value={dashboard.id}>
                            {dashboard.name}
                        </Select.Option>
                    ))}
                    <Select.Option value="new">+ New Dashboard</Select.Option>
                </Select>
            </form>
        </Modal>
    )
}
Example #18
Source File: Abis.tsx    From useDApp with MIT License 5 votes vote down vote up
export function Abis({ onNavigate }: Props) {
  const [abis, setAbis] = useUserAbis()
  const [text, setText] = useState('')
  const [error, setError] = useState('')

  function onSubmit(e: FormEvent) {
    e.preventDefault()
    try {
      const entries = parseAbiInput(text)
      if (entries.length > 0) {
        setAbis([...entries, ...abis])
      }
      setText('')
      setError('')
    } catch {
      setError('Cannot parse input data')
    }
  }

  function remove(i: number) {
    setAbis(abis.filter((x, index) => index !== i))
  }

  return (
    <Page name="abis" onNavigate={onNavigate}>
      <Wrapper>
        <Title>ABI Manager</Title>
        <Text>
          ABIs are used to parse call data. Adding ABIs from your contracts will allow you to easily inspect method
          calls that your application is making.
        </Text>
        <form onSubmit={onSubmit}>
          <TextArea value={text} onChange={(e) => setText(e.target.value)} placeholder={PLACEHOLDER} rows={6} />
          <Controls>
            <SubmitButton type="submit" value="Add ABIs" />
            <ErrorMessage>{error}</ErrorMessage>
          </Controls>
        </form>
        <AbiList>
          {getAbis(abis).map((entry, i) => (
            <AbiItem key={i} className={entry.disabled ? 'disabled' : ''}>
              <Signature className={entry.shadowed ? 'shadowed' : ''}>{entry.code}</Signature>
              {!entry.disabled && <Remove onClick={() => remove(i)}>Remove</Remove>}
            </AbiItem>
          ))}
        </AbiList>
      </Wrapper>
    </Page>
  )
}
Example #19
Source File: TemporaryStorageSwitch.tsx    From che-dashboard-next with Eclipse Public License 2.0 5 votes vote down vote up
private handleChange: (checked: boolean, event: FormEvent<HTMLInputElement>) => void;
Example #20
Source File: NewRoom.tsx    From NextLevelWeek with MIT License 5 votes vote down vote up
export function NewRoom() {
  // Tendo acesso ao usuário autenticado.
  const { user } = useAuth();

  const history = useHistory();

  const [newRoom, setNewRoom] = useState("");

  // Função de criação de uma sala.
  async function handleCreateRoom(event: FormEvent) {
    // Prevenindo o comportamento padrão do formulário.
    event.preventDefault();

    // Tendo acesso ao valor do input.
    // console.log(newRoom);
    if (newRoom.trim() === "") {
      toast.error("Room name cannot be empty.", {
        icon: "⚠️",
      });
      return;
    }

    const roomRef = database.ref("rooms");
    // "jogando" uma informação dentro de "rooms"
    const firebaseRoom = await roomRef.push({
      title: newRoom,
      authorId: user?.id,
    });

    // Após o usuário crar a sala, ele será redirecionado para a nova sala criada.
    history.push(`/rooms/${firebaseRoom.key}`);
  }

  return (
    <div id="page-auth">
      <Toaster position="top-right" reverseOrder={false} />
      <aside>
        <img
          src={illustrationImg}
          alt="Ilustração simbolizando perguntas e respostas."
        />
        <strong>Crie salas de Q&amp;E ao-vivo.</strong>
        <p>Tire as dúvidas da sua audência em tempo-real.</p>
      </aside>
      <main>
        <div className="main-content">
          <img src={logoImg} alt="Letmeask" />

          <h2>Criar uma nova sala</h2>
          <form onSubmit={handleCreateRoom}>
            <input
              type="text"
              placeholder="Nome da sala"
              onChange={(event) => setNewRoom(event.target.value)}
              value={newRoom}
            />
            <Button type="submit">Criar sala</Button>
          </form>
          <p>
            Quer entrar em uma sala existente ? <Link to="/">clique aqui</Link>
          </p>
        </div>
      </main>
    </div>
  );
}
Example #21
Source File: index.tsx    From screenshot.rocks with MIT License 5 votes vote down vote up
BrowserFrame = view((props: ICanvasProps) => {
    let browserContent;
    if (!props.showControlsOnly) {
        browserContent = props.imageData
            ? <img id="screenshot"
                   src={props.imageData}
                   alt="Screenshot.rocks browser mockup"/>
            : <ImageSelector/>
    }

    return (
        <div className={styles(props)}>
            <div className="browser-controls">
                <div className={`window-controls ${!browserStore.settings.showWindowControls ? 'hide' : ''}`}>
                    <span className="close"/>
                    <span className="minimise"/>
                    <span className="maximise"/>
                </div>
                <div className={`page-controls ${!browserStore.settings.showNavigationButtons ? 'hide' : ''}`}>
                    <span className="back browser-container">
                        <IoIosArrowBack/>
                    </span>
                    <span className="forward browser-container">
                        <IoIosArrowForward/>
                    </span>
                </div>
                <span className={`url-bar browser-container ${!browserStore.settings.showAddressBar || props.hideAddressBarOverride ? 'hide' : ''}`}>
                    <span className="lock">
                        <FiLock/>
                    </span>
                    <div className={`url-text ${!browserStore.settings.showAddressBarUrl ? 'hide' : ''}`}>
                        <span className="text-success" contentEditable suppressContentEditableWarning>
                            {browserStore.settings.addressBarUrlProtocol}
                        </span>
                        <input
                            className="urlInput"
                            value={browserStore.settings.addressBarUrl}
                            type="text"
                            onInput={(e:FormEvent<HTMLInputElement>) => {browserStore.settings.addressBarUrl = e.currentTarget.value}}>
                        </input>
                    </div>
                    </span>
                <span className={`browser-container ${!browserStore.settings.showSettingsButton ? 'hide' : ''}`}>
                    <span className="settings">
                        <IoIosOptions/>
                    </span>
                </span>
            </div>
            <div className="content-wrap">
                {browserContent}
            </div>
        </div>
    );
})
Example #22
Source File: Modal.tsx    From tobira with Apache License 2.0 5 votes vote down vote up
ConfirmationModal
    = forwardRef<ConfirmationModalHandle, PropsWithChildren<ConfirmationModalProps>>(
        ({
            title: titleOverride,
            buttonContent,
            onSubmit,
            children,
        }, ref) => {
            const { t } = useTranslation();
            const title = titleOverride ?? t("manage.are-you-sure") ?? bug("missing translation");

            const [inFlight, setInFlight] = useState(false);
            const [error, setError] = useState<JSX.Element | undefined>();

            const modalRef = useRef<ModalHandle>(null);

            useImperativeHandle(ref, () => ({
                open: () => {
                    setInFlight(false);
                    setError(undefined);
                    currentRef(modalRef).open();
                },
                done: () => {
                    currentRef(modalRef).close?.();
                },
                reportError: (error: JSX.Element) => {
                    setInFlight(false);
                    setError(error);
                },
            }));

            const onSubmitWrapper = (event: FormEvent) => {
                event.preventDefault();
                // Don't let the event escape the portal,
                //   which might be sitting inside of other `form` elements.
                event.stopPropagation();
                setInFlight(true);
                setError(undefined);
                onSubmit?.();
            };

            return <Modal title={title} closable={!inFlight} ref={modalRef}>
                {children}
                <form onSubmit={onSubmitWrapper} css={{ marginTop: 32, textAlign: "center" }}>
                    <Button disabled={inFlight} type="submit" kind="danger">
                        {buttonContent}
                    </Button>
                    {inFlight && <div css={{ marginTop: 16 }}><Spinner size={20} /></div>}
                </form>
                {boxError(error)}
            </Modal>;
        },
    )
Example #23
Source File: CreateFolderDialog.tsx    From firebase-tools-ui with Apache License 2.0 5 votes vote down vote up
CreateFolderDialog: React.FC<
  React.PropsWithChildren<NewFolderDialogProps>
> = ({ confirm, isOpen, close }) => {
  const [name, setName] = useReducer(
    (s: string, value: string) => value.trim(),
    ''
  );

  const createFolder = () => {
    confirm(name);
    close();
  };

  return (
    <Dialog open={isOpen} onClose={() => close()}>
      <DialogTitle>Create folder</DialogTitle>

      <DialogContent>
        <form
          onSubmit={(e: FormEvent) => {
            e.preventDefault();
            createFolder();
          }}
        >
          <Field
            maxLength={MAX_FOLDER_NAME_LENGTH}
            onChange={(e: FormEvent<HTMLInputElement>) => {
              setName((e.target as HTMLInputElement).value);
            }}
            required
            label="New folder name"
          />
        </form>
      </DialogContent>

      <DialogActions>
        <DialogButton type="button" theme="secondary" onClick={close}>
          Cancel
        </DialogButton>

        <DialogButton disabled={name === ''} unelevated onClick={createFolder}>
          Create
        </DialogButton>
      </DialogActions>
    </Dialog>
  );
}
Example #24
Source File: SearchFilterBar.tsx    From ace with GNU Affero General Public License v3.0 5 votes vote down vote up
SearchFilterBar: FC<SearchFilterBarProps> = ({ filters }) => {
    const [userInput, setUserInput] = useState('');
    const [autocompleteElements, setAutocompleteElements] = useState<AutocompleteElement[]>([]);

    const handleUserInput = (e: FormEvent<HTMLInputElement>) => setUserInput(e.currentTarget.value);

    useEffect(() => {
        if (userInput.length > 0) {
            const exactFilterMatch = filters.find((it) => it.key === userInput);

            if (exactFilterMatch) {
                setAutocompleteElements(exactFilterMatch.possibleValues.map((it) => ({
                    value: (
                        <>
                            <span>{exactFilterMatch.key}</span>
                            <span>:</span>
                            <span className="text-teal-light">{it}</span>
                        </>
                    ),
                    description: `Events from instrument '${it}'`,
                })));
            } else {
                const autocompleteFilters = filters.filter((it) => it.key.startsWith(userInput));

                setAutocompleteElements(autocompleteFilters.map((it) => ({
                    value: it.key,
                    description: it.description,
                })));
            }
        }
    }, [userInput]);

    return (
        <>
            <input onInput={handleUserInput} />

            {autocompleteElements.length > 0 && (
                <div className="relative w-full h-0">
                    <div className="w-full flex flex-col gap-y-2 mt-2 py-1.5 bg-gray-800 rounded-md shadow-lg">
                        {autocompleteElements.map((it) => (
                            <AutocompleteElementRender element={it} />
                        ))}
                    </div>
                </div>
            )}
        </>
    );
}
Example #25
Source File: index.tsx    From nlw2-proffy with MIT License 5 votes vote down vote up
function TeacherList() {
    const [teachers, setTeachers] = useState([]);

    const [subject, setSubject] = useState('');
    const [week_day, setWeekDay] = useState('');
    const [time, setTime] = useState('');

    async function searchTeachers(e: FormEvent) {
        e.preventDefault();

        const response = await api.get('classes', {
            params: {
                subject,
                week_day,
                time,
            }
        });
        setTeachers(response.data);
    }

    return (
        <div id="page-teacher-list" className="container">
            <PageHeader title="Estes são os proffys disponíveis.">
                <form id="search-teachers" onSubmit={searchTeachers}>
                <Select
                        name="subject"
                        label="Dia da semana"
                        value={subject}
                        onChange={e => { setSubject(e.target.value)}}
                        options={[
                            {value: 'Programação', label: 'Programação'},
                            {value: 'Análise de Circuitos Elétricos', label: 'Análise de Circuitos Elétricos'},
                            {value: 'Cálculo Diferencial e Integral', label: 'Cálculo Diferencial e Integral'},
                            {value: 'Eletromagnetismo', label: 'Eletromagnetismo'},
                            {value: 'Eletrônica Digital', label: 'Eletrônica Digital'},
                            {value: 'Propagação de Ondas e Guias', label: 'Propagação de Ondas e Guias'},
                        ]} />
                        <Select
                        name="week_day"
                        label="Matéria"
                        value={week_day}
                        onChange={e => { setWeekDay(e.target.value)}}
                        options={[
                            {value: '0', label: 'Domingo'},
                            {value: '1', label: 'Segunda-feira'},
                            {value: '2', label: 'Terça-feira'},
                            {value: '3', label: 'Quarta-feira'},
                            {value: '4', label: 'Quinta-feira'},
                            {value: '5', label: 'Sexta-feira'},
                            {value: '6', label: 'Sábado'},
                        ]} />
                    <Input 
                    type="time" 
                    name="time" 
                    label="Hora"
                    value={time}
                    onChange={e => { setTime(e.target.value)
                    }} />

                    <button type="submit">
                        Buscar
                    </button>
                </form>
            </PageHeader>

            <main>
                {teachers.map((teacher: Teacher) => {
                    return <TeacherItem 
                    key={teacher.id}
                    teacher={teacher} />
                })}
            </main>
        </div>
    )
}
Example #26
Source File: intro.tsx    From desktop with MIT License 5 votes vote down vote up
export function OnboardingIntro({ onGoNext }: IProps): JSX.Element {
  const onSubmit: React.FocusEventHandler<HTMLFormElement> = (e) => {
    e.preventDefault()
    onGoNext()
  }

  const [optedIn = false, setOptedIn] = useConfig(`telemetryOptIn`)

  console.log({ optedIn })

  const onToggle = useCallback(
    (e: FormEvent<HTMLInputElement>): void => {
      setOptedIn(e.currentTarget.checked)
    },
    [setOptedIn]
  )

  return (
    <div
      sx={{
        maxWidth: `62rem`,
      }}
    >
      <Heading
        sx={{
          fontFamily: `sans`,
          fontSize: 9,
          fontWeight: `extraBold`,
          lineHeight: `dense`,
          letterSpacing: `-0.02em`,
          color: `grey.90`,
          marginBottom: 10,
        }}
      >
        <span
          sx={{
            display: `block`,
            color: `grey.60`,
            fontWeight: `normal`,
            fontSize: 1,
            lineHeight: `dense`,
          }}
        >
          Welcome to
        </span>
        Gatsby Desktop
      </Heading>
      <form onSubmit={onSubmit}>
        <Text sx={{ maxWidth: `20rem`, mt: 0, mb: 7 }}>
          Would you like to help us improve Gatsby Desktop by periodically
          submitting anonymous usage information?
        </Text>
        <CheckboxFieldBlock
          id="anonUsage"
          name="anonUsage"
          label="Yes, help improve Gatsby Desktop"
          onChange={onToggle}
          checked={optedIn}
        />
        <Button
          type="submit"
          rightIcon={<MdArrowForward />}
          size="L"
          sx={{ mt: 8 }}
        >
          Get started
        </Button>
      </form>
    </div>
  )
}
Example #27
Source File: AuctionModal.tsx    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
function AuctionModal({ close }: Props) {
  const { id } = useParams() as Params;

  const { values, handleChange } = useForm({ minPrice: '', duration: '', bidPeriod: '' });
  const { minPrice, duration, bidPeriod } = values;

  const sendMessage = useMarketplaceMessage();

  const getMilliseconds = (value: string) => Number(value) * MILLISECONDS_MULTIPLIER;

  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (minPrice && duration) {
      const payload = {
        CreateAuction: {
          nftContractId: NFT_CONTRACT_ADDRESS,
          ftContractId: null,
          tokenId: id,
          duration: getMilliseconds(duration),
          bidPeriod: getMilliseconds(bidPeriod),
          minPrice,
        },
      };

      sendMessage(payload).then(close);
    }
  };

  return (
    <Modal heading="Auction" close={close}>
      <form className={styles.form} onSubmit={handleSubmit}>
        <Input placeholder="min price" name="minPrice" value={minPrice} onChange={handleChange} />
        <Input placeholder="duration (min)" name="duration" value={duration} onChange={handleChange} />
        <Input placeholder="bid period (min)" name="bidPeriod" value={bidPeriod} onChange={handleChange} />
        <Button type="submit" text="Start auction" block />
      </form>
    </Modal>
  );
}
Example #28
Source File: index.tsx    From nextjs-hasura-boilerplate with MIT License 5 votes vote down vote up
MyAccountPageComponent = ({ user }) => {
  const [name, setName] = useState(user.name);
  const [session] = useSession();
  const [updateUser, { loading: updateUserFetching, error: updateUserError }] =
    useUpdateUserMutation();

  const handleSubmit = () => {
    updateUser({
      variables: {
        userId: session.id,
        name,
      },
    });
  };

  const errorNode = () => {
    if (!updateUserError) {
      return false;
    }

    return (
      <Alert status="error">
        <AlertIcon />
        <AlertTitle>{updateUserError}</AlertTitle>
        <CloseButton position="absolute" right="8px" top="8px" />
      </Alert>
    );
  };

  return (
    <Stack spacing={8}>
      <Heading>My Account</Heading>
      {errorNode()}
      <Box shadow="lg" rounded="lg" p={4}>
        <Stack spacing={4}>
          <FormControl isRequired>
            <FormLabel htmlFor="name">Name</FormLabel>
            <Input
              type="text"
              id="name"
              value={name}
              onChange={(e: FormEvent<HTMLInputElement>) =>
                setName(e.currentTarget.value)
              }
              isDisabled={updateUserFetching}
            />
          </FormControl>
          <FormControl>
            <Button
              loadingText="Saving..."
              onClick={handleSubmit}
              isLoading={updateUserFetching}
              isDisabled={!name.trim()}
            >
              Save
            </Button>
          </FormControl>
        </Stack>
      </Box>
    </Stack>
  );
}
Example #29
Source File: add-new-feed-form.tsx    From nextjs-strapi-boilerplate with MIT License 5 votes vote down vote up
AddNewFeedForm = () => {
  const { colorMode } = useColorMode();
  const bgColor = { light: "white", dark: "gray.800" };
  const color = { light: "gray.800", dark: "gray.100" };
  const [body, setBody] = useState("");
  const { data:session, status } = useSession();

  if (!session) {
    return (
      <AccessDeniedIndicator message="You need to be signed in to add a new feed!" />
    );
  }

  const [
    insertFeed,
    { loading: insertFeedFetching, error: insertFeedError },
  ] = useMutation(insertFeedMutation);

  const handleSubmit = async () => {
    await insertFeed({ variables: { userId: session.id, body } });

    setBody("");
  };

  const errorNode = () => {
    if (!insertFeedError) {
      return false;
    }

    return (
      <Alert status="error">
        <AlertIcon />
        <AlertTitle>{insertFeedError.message}</AlertTitle>
        <CloseButton position="absolute" right="8px" top="8px" />
      </Alert>
    );
  };

  return (
    <Stack spacing={4}>
      {errorNode()}
      <Box
        p={4}
        bg={bgColor[colorMode]}
        color={color[colorMode]}
        shadow="lg"
        rounded="lg"
      >
        <Stack spacing={4}>
          <FormControl isRequired>
            <FormLabel htmlFor="body">What's on your mind?</FormLabel>
            <Textarea
              id="body"
              value={body}
              onChange={(e: FormEvent<HTMLInputElement>) =>
                setBody(e.currentTarget.value)
              }
              isDisabled={insertFeedFetching}
            />
          </FormControl>
          <FormControl>
            <Button
              loadingText="Posting..."
              onClick={handleSubmit}
              isLoading={insertFeedFetching}
              isDisabled={!body.trim()}
            >
              Post
            </Button>
          </FormControl>
        </Stack>
      </Box>
    </Stack>
  );
}