Events & Forms

Events

import React, { FC, useState } from 'react'

export const Events: FC = () => {
  const [lastEvent, setLastEvent] = useState('N/A')
  return (
    <div>
      <input
        aria-label="try copy/pasting"
        defaultValue="try copy/pasting"
        onFocus={() => setLastEvent('onFocus')}
        onBlur={() => setLastEvent('onBlur')}
        onCopy={() => setLastEvent('onCopy')}
        onCut={() => setLastEvent('onCut')}
        onPaste={() => setLastEvent('onPaste')}
        onKeyDown={() => setLastEvent('onKeyDown')}
        onKeyUp={() => setLastEvent('onKeyUp')}
      />
      <pre>last event: {lastEvent}</pre>
    </div>
  )
}

export default <Events />
last event: N/A

Forms

  • use value & onChange props to control form items
import React, { ChangeEvent, FC, useState } from 'react'

export const SimpleInput: FC = () => {
  const [value, setValue] = useState('default value')
  const onChange = (event: ChangeEvent<HTMLInputElement>) => {
    setValue(event.target.value)
  }

  return (
    <div>
      <label>
        simple input
        <input type="text" value={value} onChange={onChange} />
      </label>
      <pre>{value}</pre>
      <button type="button" onClick={() => setValue('new value')}>
        change to `new value`
      </button>
    </div>
  )
}

export default <SimpleInput />
default value
  • with multiple form items
import React, { FC, useState } from 'react'
import { UserAPI } from './user-api'

export const SimpleForm: FC = () => {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [terms, setTerms] = useState(false)
  const [submitted, setSubmitted] = useState(false)

  return (
    <form
      aria-label="registration form"
      onSubmit={async (event) => {
        event.preventDefault()
        setSubmitted(true)
        try {
          await UserAPI.register({ username, password })
          // redirect to profile
        } catch {
          // show error
        }
      }}
    >
      <div>
        <label>
          Username
          <input
            type="text"
            name="username"
            value={username}
            onChange={(event) => setUsername(event.target.value)}
          />
        </label>
      </div>
      <div>
        <label>
          Password
          <input
            type="password"
            name="password"
            value={password}
            onChange={(event) => setPassword(event.target.value)}
          />
        </label>
      </div>
      <div>
        <label>
          <input
            type="checkbox"
            name="terms"
            checked={terms}
            onChange={(event) => setTerms(event.target.checked)}
          />
          <span>I have read the Terms and Conditions</span>
        </label>
      </div>
      <button type="submit">Register</button>
      <pre>
        {JSON.stringify({ username, password, terms, submitted }, null, '  ')}
      </pre>
    </form>
  )
}

export default <SimpleForm />
{
  "username": "",
  "password": "",
  "terms": false,
  "submitted": false
}
import { Field, FieldProps, Form, Formik } from 'formik'
import React, { FC } from 'react'
import { UserAPI } from './user-api'

export const SimpleFormik: FC = () => {
  return (
    <Formik
      initialValues={{
        username: '',
        password: '',
        terms: false,
        submitted: false,
      }}
      onSubmit={async ({ username, password }, { setFieldValue }) => {
        setFieldValue('submitted', true)
        try {
          await UserAPI.register({ username, password })
          // redirect to profile
        } catch {
          // show error
        }
      }}
    >
      <Form aria-label="registration form">
        <div>
          <label>
            Username
            <Field name="username" />
          </label>
        </div>
        <div>
          <label>
            Password
            <Field type="password" name="password" />
          </label>
        </div>
        <div>
          <label>
            <Field type="checkbox" name="terms" />
            <span>I have read the Terms and Conditions</span>
          </label>
        </div>
        <button type="submit">Register</button>
        <Field>
          {({ form }: FieldProps) => (
            <pre>{JSON.stringify(form.values, null, '  ')}</pre>
          )}
        </Field>
      </Form>
    </Formik>
  )
}

export default <SimpleFormik />
{
  "username": "",
  "password": "",
  "terms": false,
  "submitted": false
}