Forms are the most important part of every application. Be it a hospital management web application, school management desktop software, website with user registrations, gmail, a mobile gaming app asking for email and user name etc., forms are everywhere.
An HTML form contains elements such as text box, checkbox, radio buttons, drop downs embedded inside form tag. A form once filled by the user is submitted to the server where the all the data is sent to the server. For better understanding, let us create a form first.

<form>
     <label>Enter name: </label>
     <input type="text" name="name" /><p/>
     <label>Enter age: </label>
     <input type="text" name="age" /><p/>
     <label>Select technology: </label>
     <select>
         <option value="react">React</option>
         <option value="angular">Angular</option>
         <option value="vue">Vue</option>
     </select><p/>
     <button type="submit">Submit</button>
 </form>

Above form has 2  input fields, drop down and a submit button.
React forms
Above form when submitted sends data to the server and navigates to a new page but since most react applications are Single Page Applications, we need some mechanism that when the form is submitted, the control still remains on the same page.
For this, it is better to create a function that is called when the form is submitted. This function has access to all the elements of the form and their values. Generally, react component’s state object is synchronized with form element values. As each form element’s value changes, the state object is updated using setState method so that at any time the state object contains updated values of form elements. When the form is submitted, the state object can directly be accessed and sent to the server. HTTP calls that we learnt in the last section are utilized for this.
Also, each element should have a handler function associated with it so that when its value changes, it directly updates the state object.
With these changes, the modified form will look like.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class FormComponent extends Component {
    // state object
    state = {
        name: null,
        age: null,
        technology: 'react'
    }

    // handler function for name 
    nameChange = (event) => {
        this.setState({name:event.target.value})
    }

    // handler function for age
    ageChange = (event) => {
        this.setState({age:event.target.value})
    }

    // handler function for technology
    technologyChange = (event) => {
        this.setState({technology:event.target.value})
    }
    
    // submit function
    formSubmit = (event) => {
        event.preventDefault();
        console.log(this.state);
    }

    render() {
        return (
            <form onSubmit = {this.formSubmit}>
                <label>Enter name: </label>
                <input type="text" name="name" 
                       onChange={this.nameChange} /><p/>
                <label>Enter age: </label>
                <input type="text" name="age" 
                       onChange={this.ageChange} /><p/>
                <label>Select technology: </label>
                <select value={this.state.technology} 
                       onChange={this.technologyChange}>
                    <option value="react">React</option>
                    <option value="python">Python</option>
                    <option value="vue">Vue</option>
                </select><p/>
                <button type="submit">Submit</button>
            </form>
        );
    }
}
ReactDOM.render(<FormComponent/>, document.getElementById('root'));

Every form element has a corresponding handler function which updates the state object with its current value. You should be using a common handler function for all the elements. Also note that the keys of state object match the name attribute of form elements. This is not required in this case since we are using custom function to submit the form.
The form itself has a submit handler function. Note the preventDefault function inside the form submit function. It prevents the default action of submit event which is refreshing the page so that the control remains on the same page. In this example, we are just logging the form to the console but in real world applications, the object is sent to the server for saving it to the database.
It is not mandatory to use the component’s state object to contain the form element values, you can use any object and update it. But using state object gives you the ease of updating element values using setState method. This becomes pretty convenient when the form is complex and contains nested elements. In these cases, the corresponding object also becomes complex.
When the form is submitted, following is the output on the console. You can guess the values entered.

{name: “Mark Twain”, age: “30”, technology: “react”}
     age30
     nameMark Twain
     technologyreact

select Tag
The HTML select tag is used to create a drop down of options. A normal select tag is created as below.

<select>
   <option value="react">React</option>
   <option value="python" selected>Python</option>
   <option value="vue">Vue</option>
</select>

Note that second option has a selected attribute. This makes the second option appear as selected when the drop down is rendered.
In react, there is no selected attribute, it instead uses a value attribute directly on the select tag. Option whose value matches the select tag’s value is shown selected.
In our example, note that we have set the select tag’s value to the technology attribute of the state object whose default value is react. Thus, when the form is rendered, react option appears to be selected.

For multiple select boxes, you need to pass an array to its value and set its multiple attribute to true as
<select multiple={true} value={[‘python‘, ‘react‘]}>
Checkbox
A checkbox is different in that it does not have a value attribute but has 2 states checked or unchecked. In order to determine whether a checkbox is checked or not, we can use the checked property from event.target of its handler function. This property will return true if the checkbox is checked false otherwise as shown below.

state = {
   updates: false
}

checkBoxHandler = (event) => {
   this.setState({updates: event.target.checked})
}

<input type="checkbox" onChange={this.checkBoxHandler} />

For any queries/doubts/additions, comment in the section below.

0

Share your thoughts !!

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.