Contenido del Curso
Expert React
Expert React
Form Submission
Step 8: Implement the form submission
We will use Formik's onSubmit
property to handle the form submission logic. As we don't have an actual backend, we will simulate the submission by alerting the form data and displaying it in the console.
Code exaplanation:
- Line 6: We define the
onSubmit
callback function that takes two arguments:values
and{ resetForm }
. Thevalues
argument contains the current values of the form fields. - Line 7-8: We extract the
username
andoccupation
values from thevalues
object and assign them to the variablesuserName
anduserOccupation
, respectively. - Line 9: The
console.log
statement logs a message to the console, displaying the user's name and occupation. Template literals are used to concatenate the values ofuserName
anduserOccupation
into the log message. - Line 10: The
alert
function displays a pop-up alert with the user's name and occupation, visually confirming the form submission. - Line 11: The
resetForm
function is called to reset the form fields to their initial values. By callingresetForm()
, the form fields will be updated with the initial values specified in theinitialValues
object.
Note
If you attempt to manually reset the form by assigning empty strings (
""
) as the initial values, it won't work, and the form fields will retain their current values. Instead, use theresetForm
function provided by Formik to ensure proper form reset.
Complete code
Feel free to examine the complete app code to understand better how the form submission logic is implemented and see the code in action.
¡Gracias por tus comentarios!