Back to: ReactJS Tutorials
Handling Form Submission in React:
In this article, I am going to discuss Handling Form Submission in React with Examples. Please read our previous article where we discussed Creating a Shared Handler Function in React.
Handling Form Submission in React:
In the last few articles, we have spent a lot of time on the state concept and we’ve seen a lot of alternatives. But it was not too much with the state. So that’s what we want to change now. Now we want to make sure that this form can be submitted when the ‘Add Expense’ button is pressed,
When this button is pressed then we gather the different state slices here and combine them into one object and then log to the console. We can use this object for different purposes but here we will just log it to the console to show you how things work. Therefore, we have to listen to the form being submitted.
Adding onClick listener to the ‘Add Expense’ button:
We can add a click listener to the Add Expense button.
But this will not be the best way of listening because there is a default behavior built into the browser and built into forums on web pages, if a button, especially a type submit, is pressed inside of a form, the overall form element will emit an event to which we can listen and that’s the submit event. So it’s on this form where we want to react to onSubmit and then execute some function whenever this form is being submitted.
Now, we will add a function here that is ‘submitHandler’. So, we just point at submit handler as we did it for all the other events as well.
Now, the thing here is that we just said that this is a default browser behavior and unfortunately, a part of this default browser behavior is that if you do click this button, the page reloads because the browser automatically sends a request whenever a form is submitted to the server which is hosting this webpage. So, in this case, to this development server.
We don’t want our webpage to reload when the form is submitted. Instead, we want to handle the form submission with Java script and manually collect and combine the data and do something with it.
So, we can disable or prevent this default behavior because we again get an event object in the parameter of the submitHandler function, automatically just as for the change events, and on this object, we can call a preventDefault () method.
This is built into JavaScript, nothing reacts specific. This is the default JavaScript behavior. We can prevent the default of this request being sent and since that request is not sent, now the page will not reload because we stay on the currently loaded page without sending any request anywhere and we can continue handling this with Javascript.
Therefore, now, we can create our, let’s say expense data object and now we’ll combine all the entered data. If you used one state approach instead of the free States approach, you already have a combined object but we don’t have that here. So, now, we will create it once the form is submitted.
Here, we simply added a title and set this to the value stored in the enteredTitle state, then we added an amount property and set this to enteredAmount and we have a date property and we set this to a new date object, constructed a new date with the built-in date constructor, then inside it, we passed the enteredDate which will parse that date string and converted into a date object.
Now, these property names here, title, amount, and date are up to you because this is your object. And enteredTitle, enteredAmount, and enteredDate points at the state variables. If you used the combined approach, you may have to re-map the property names because later in the app, we’re relying on the title, amount, and date property name.
So make sure that these property names exist and hold the correct value. So, for now, we’re just console.log the expense data so that we can see that.
Now, if you save everything, write anything in the input of title, amount and pick any date,
Now, if we hit on the ‘Add Expense’ Button, then in the console section, we will see,
Here, we got this object which has all that data stored. So, all things work fine. We are reacting to the form submission. Now, I also want to clear the input fields in the form to delete the entered values when that form is submitted. So, we will see this in the next article.
Full Code of ExpenseForm.js:
import React, { useState } from "react"; import "./ExpenseForm.css"; const ExpenseForm = () => { const [enteredTitle, setEnteredTitle] = useState(""); const [enteredAmount, setEnteredAmount] = useState(""); const [enteredDate, setEnteredDate] = useState(""); // const[userInput, setUserInput] = useState({ // enteredTitle: '', // enteredAmount: '', // enteredDate: '' // }); const titleChangeHandler = (event) => { setEnteredTitle(event.target.value); // setUserInput({ // ...userInput, // enteredTitle: event.target.value // }) // setUserInput((prevState) => { // return {...prevState, enteredTitle: event.target.value}; // }); }; const amountChangeHandler = (event) => { setEnteredAmount(event.target.value); // setUserInput({ // ...userInput, // enteredAmount: event.target.value // }) // setUserInput((prevState) => { // return {...prevState, enteredAmount: event.target.value}; // }); }; const dateChangeHandler = (event) => { setEnteredDate(event.target.value); // setUserInput({ // ...userInput, // enteredDate: event.target.value // }) // setUserInput((prevState) => { // return {...prevState, enteredDate: event.target.value}; // }); }; // const inputChangeHanlder = (identifier, value) => { // if (identifier == "title") { // setEnteredTitle(value); // } else if (identifier == "date") { // setEnteredDate(value); // } else { // setEnteredAmount(value); // } // }; const submitHandler = (event) => { event.preventDefault(); const expenseData = { title: enteredTitle, amount: enteredAmount, date: new Date(enteredDate) }; console.log(expenseData); }; return ( <form onSubmit={submitHandler}> <div className="new-expense__controls"> <div className="new-expense__control"> <label>Title</label> <input type="text" onChange={titleChangeHandler} /> </div> <div className="new-expense__control"> <label>Amount</label> <input type="number" onChange={amountChangeHandler} min="0.01" step="0.01" /> </div> <div className="new-expense__control"> <label>Date</label> <input type="date" onChange={dateChangeHandler} min="2023-06-25" max="2025-12-31" /> </div> </div> <div className="new-expense__actions"> <button type="submit">Add Expense</button> </div> </form> ); }; export default ExpenseForm;
In the next article, I am going to discuss Two-Way Binding in React with Examples. Here, in this article, I try to explain Handling Form Submission in React with Examples. I hope you enjoy this Handling Form Submission in React article.