sajad torkamani

Given this component:

import React from 'react'
import { useField } from 'formik'

interface Props {
  name: string
  label?: string
  type?: string
}

const TextInput: React.FC<Props> = ({ name, label, ...props }) => {
  const [field, { touched, error }] = useField(name)
  const id = `field_${name}`

  return (
    <>
      {label && (
        <label htmlFor={id} className="block mb-0.5">
          {label}
        </label>
      )}

      <input
        {...field}
        {...props}
        id={id}
        className="border w-full py-1 px-2"
      />

      {touched && error && (
        <div className="text-red-600 text-sm mt-0.5">{error}</div>
      )}
    </>
  )
}

TextInput.defaultProps = {
  type: 'text',
}

export default TextInput

You can reuse it like so:

<Formik
  initialValues={{ email: "", password: "" }}
  validationSchema={ValidationSchema}
  onSubmit={handleSubmit}
>
  {({ status, isSubmitting }) => (
    <>
      <Form>
        {status && <FormStatus>{status}</FormStatus>}

        <TextInput name="email" label="Email" />
        <TextInput name="password" label="Password" type="password" />

        <Button type="submit" disabled={isSubmitting}>
          Submit
        </Button>
      </Form>
    </>
  )}
</Formik>;

Leave a comment

Your email address will not be published. Required fields are marked *