Reusable Formik text input component
11 March 2022 (Updated 4 April 2022)
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>;
Tagged:
React tooling
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment