Formik is a library that makes form handling in React apps easy.
In this article, we’ll look at how to handle form inputs with Formik.
Checkboxes
We can bind checkbox values to states with Formik.
For instance, we can write:
import React from "react";
import { Formik, Form, Field } from "formik";
export const FormExample = () => (
<div>
<Formik
initialValues={{
toggle: false,
checked: []
}}
onSubmit={(values) => {
alert(JSON.stringify(values, null, 2));
}}
>
{({ values }) => (
<Form>
<label>
<Field type="checkbox" name="toggle" />
{`${values.toggle}`}
</label>
<div>Checked</div>
<div>
<label>
<Field type="checkbox" name="checked" value="apple" />
apple
</label>
<label>
<Field type="checkbox" name="checked" value="orange" />
orange
</label>
<label>
<Field type="checkbox" name="checked" value="grape" />
grape
</label>
</div>
<button type="submit">Submit</button>
</Form>
)}
</Formik>
</div>
);
export default function App() {
return (
<div className="App">
<FormExample />
</div>
);
}
We set the initialValues
to what we want.
In the first Field
component, we set name
to 'toggle'
to bind to the toggle field.
This will bind the checked value to the values.toggle
property.
It’ll be true
when it’s checked and false
otherwise.
In the div, we have 3 Field
components.
We set the value
in addition to the name
to let us populate the checked
array with the value
prop value of the checkboxes that are checked.
When we submit the form, we see the checked items in checked
and toggle
is either true
or false
depending on whether it’s checked or not.
Radio Buttons
Formik also makes binding states to radio buttons easy.
To do this, we write:
import React from "react";
import { Formik, Form, Field } from "formik";
export const FormExample = () => (
<div>
<Formik
initialValues={{
picked: ""
}}
onSubmit={(values) => {
alert(JSON.stringify(values, null, 2));
}}
>
{({ values }) => (
<Form>
<div>Picked</div>
<div>
<label>
<Field type="radio" name="picked" value="apple" />
One
</label>
<label>
<Field type="radio" name="picked" value="orange" />
Two
</label>
<div>Picked: {values.picked}</div>
</div>
<button type="submit">Submit</button>
</Form>
)}
</Formik>
</div>
);
export default function App() {
return (
<div className="App">
<FormExample />
</div>
);
}
We set the name
of the radio button groups to the same name.
And we also set the value
for each.
Then we can pick one radio from the ones with the same name
value.
And we’ll see the value with the value.picked
property.
Conclusion
We can bind checkbox and radio button values to states with Formik.