Getting input values on form submission in react.js.
Hello, in this post I am going to show you how you can get the values of all the fields in your form on submission in a react.js application.
Alright , first thing we have to do is to create a basic function as shown below
function submitHandler(e){
e.preventDefaullt()
}
e.prevenDefault prevents the normal submission process of our form. Now on to the next part we'll return to this later.
Next step is to create a basic html form with input field, text-field and select field as shown below
<form className={`${styles.form}`} onSubmit={submitHandler}>
<label htmlFor="#username"> Name</label>
<input className={`${styles.input}`}
placeholder="Enter contact name"
type={"text"}
id="username"
name="username"
/>
<label htmlFor="#short_description"> Short Info</label>
<textarea className={`${styles.textarea}`}
placeholder="Enter contact address"
type={"text"}
id="short_description"
name="short_description"
/>
<label htmlFor="#gender">Select gender</label>
<select name="gender" id="gender">
<option defaultValue={"opt1"}>Male</option>
<option defaultValue={"opt2"}>Female</option>
</select>
<br />
<div style={{ display: "flex", justifyContent: "center" }}>
<button type="submit">Submit</button>
</div>
</form>
Notice the onSubmit attribute in the form tag in the code above. This calls the handleSubmit fuction we created earlier when the submit button of the form is clicked on.
Notice also that each field above has a unique name attribute and a unique id attribute, ensure to add those attributes to each of your form field. Its important for the method we are using to work.
Add some css for a little bit of styling.
.main{
width: 100vw;
min-height: 100vh;
display: grid;
justify-content: center;
align-items: center;
background: #8a2be2;
}
.form{
display: grid;
color: white;
width: 50vw;
}
.input{
min-height: 6vh;
border-radius: 10px;
}
.textarea{
min-height: 15vh;
border-radius: 10px;
}
Alright now back to the main function we created, update your code to
function submitHandler(e) {
e.preventDefault();
var formData = new FormData(e.target);
const form_values = Object.fromEntries(formData);
console.log('form values', form_values)
}
Now run your development server then populate the input fields of your form with dummy content, click on the submit buttton then check your browser console window, the data you inputed should be consoled out with each field having a key of the name we specified.
Conclusion
We have been able to get the vaulues of all the data inputed or selected by the user. This method also works in plain valnilla javacript. Thanks for reading, if you have any questions about the post, feel free to leave a comment down below and i will reply youi as soon as i can.