Course Content
Expert React
Expert React
4. Formik
6. Next Steps
Involve Formik into React component
Step 5: Create form markup
Let's start by creating the basic markup for our form. We will have two input fields: one for the user's name and another for their occupation.
Code explanation: We return a simple form with two input fields, one for the user's name and another for their occupation.
Step 6: Embed Formik
To leverage the power of Formik, we need to integrate its built-in tools into our form component.
Code explanation:
- Line 2: The
<form>
element has anonSubmit
prop set toformik.handleSubmit
, a function provided by the Formik library. It is called when the form is submitted. - Line 3-9: Configuration for the first input field.
- Line 4: The input field is of type text.
- Line 5: The
name
prop set tousername
. This is used to identify the input field within the form. - Line 6: The
placeholder
prop sets the placeholder text toName
. - Line 7: The
onChange
prop is set toformik.handleChange
, another function that Formik provides. It updates the form's state whenever the input value changes. - Line 8: The
value
prop is set toformik.values.username
, which represents the current value of the input field based on the form's state.
- Line 10-16: Configuration for the second input field.
- Line 11: The input field is of type text.
- Line 12: The
name
prop set tooccupation
. - Line 13: The
placeholder
prop sets the placeholder text toOccupation
. - Line 14: The
onChange
prop is set toformik.handleChange
. - Line 15: The
value
prop is set toformik.values.occupation
, which represents the current value of the input field based on the form's state.
Note
Ensuring that the
name
prop value of the<input>
element and the last word in the correspondingvalue
prop match is vital. This matching allows Formik to correctly associate the input field with the appropriate value in the form's state, enabling Formik to track and manage the input field's value based on its name.
Complete code
Everything was clear?