Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Involve Formik into React component | Formik
Expert React
course content

Conteúdo do Curso

Expert React

Expert React

1. React Key Concepts
2. React Router
3. Redux Toolkit
4. Formik
5. Jest
6. Next Steps

bookInvolve 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 an onSubmit prop set to formik.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 to username. This is used to identify the input field within the form.
    • Line 6: The placeholder prop sets the placeholder text to Name.
    • Line 7: The onChange prop is set to formik.handleChange, another function that Formik provides. It updates the form's state whenever the input value changes.
    • Line 8: The value prop is set to formik.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 to occupation.
    • Line 13: The placeholder prop sets the placeholder text to Occupation.
    • Line 14: The onChange prop is set to formik.handleChange.
    • Line 15: The value prop is set to formik.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 corresponding value 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

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 4
We're sorry to hear that something went wrong. What happened?
some-alt