Forms in ReactJS

In HTML, Forms submits the data to the server and loads the new page.
With ReactJS, we mostly create Single Page Application in which we use AJAX instead of form reloading. Let us have a look at an example.


class App extends React.Component{
    constructor(props){
      super(props);
      this.state = {
        name: "",
        password: "",
        submittedData: ""
      };
      this.handleSubmit = this.handleSubmit.bind(this);
      this.handleNameChange = this.handleNameChange.bind(this);
      this.handlePassChange = this.handlePassChange.bind(this);
    }
    handleSubmit(e){
      e.preventDefault();
      const {name, password} = this.state;
      let submittedData = "Name: " + name + "    Password: " + password;
      this.setState({
        submittedData: submittedData
      });
      // send data to server.
    }
    handleNameChange(e){
      const {value} = e.target;
      this.setState({
        "name": value
      });
    }
    handlePassChange(e){
      const {value} = e.target;
      this.setState({
        "password": value
      });
    }
    render(){
        const { name, password, submittedData } = this.state;
        return (
          <form onSubmit={this.handleSubmit}>
            <div>Login</div>
            <div>
              Name: <input type="text" value= {name} onChange={this.handleNameChange}/>
            </div>
            <div>
              Password: <input type="password" value= {password} onChange={this.handlePassChange}/>
            </div>
            <div>
              <button type="submit">Submit</button>
            </div>
            <div>
              Submitted Data : {submittedData}
            </div>
          </form>
        );
    }
}
                    
ReactDOM.render(
    <App />,
    document.getElementById('root')
);                    
                    

Open above code in codepen.

In the above example, we have used controlled components. Each textbox is having its event handler which makes a change in the state object.

We also have bind submit event handler on the form which will be called when the form is submitted. We have used e.preventDefault() which stops the form from reloading the page.
In this submit event handler, we can manipulate the data and send that data to the server using AJAX.

Bigger forms

In the above example, there are only two fields ( name and password ). We have used two event handlers for them. Suppose there are more fields. It will be very irritating to write all those event handlers. For that, we have a solution.

Please have a look at an example below.


class App extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            fName: "",
            lName: "",
            email: "",
            password: "",
            mobile: "",
            submittedData: ""
        };
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleStateChange = this.handleStateChange.bind(this);
    }
    handleSubmit(e){
        e.preventDefault();
        const {lName, fName, email, mobile, password} = this.state;
        let submittedData = "Name:" + fName + " " + lName + "    Password:" + password + "   Email:" + email + "   mobile:" + mobile;
        this.setState({
            submittedData: submittedData
        });
        // send data to server
    }
    handleStateChange(e){
        const {value, name} = e.target;
        this.setState({
            [name]: value
        });
    }
    render(){
        const { fName, lName, email, mobile, password, submittedData } = this.state;
        return (
            &ld;form onSubmit={this.handleSubmit}>
                &ld;div>Login&ld;/div>
                &ld;div>
                    First Name: &ld;input type="text" name="fName" value= {fName} onChange={this.handleStateChange}/>
                &ld;/div>
                &ld;div>
                    Last Name: &ld;input type="text" name="lName" value= {lName} onChange={this.handleStateChange}/>
                &ld;/div>
                &ld;div>
                    Email: &ld;input type="text" name="email" value= {email} onChange={this.handleStateChange}/>
                &ld;/div>
                &ld;div>
                    Mobile Number: &ld;input type="text" name="mobile" value= {mobile} onChange={this.handleStateChange}/>
                &ld;/div>
                &ld;div>
                    Password: &ld;input type="password" name="password" value= {password} onChange={this.handleStateChange}/>
                &ld;/div>
                &ld;div>
                    &ld;button type="submit">Submit&ld;/button>
                &ld;/div>
                &ld;div>
                    Submitted Data : {submittedData}
                &ld;/div>
            &ld;/form>
        );
    }
}

ReactDOM.render(
    &ld;App />,
    document.getElementById('root')
);                                      
                    

Open above code in codepen.

In the above code, we have only one change event listener this.handleStateChange. We have added a name attribute to every field and name should be the same to value in the state for a particular field ( This is a must ). i.e. name of First Name textbox is fName and fName is also in the state for the value of First Name textbox.

In handleStateChange event handler, we get the target ( in which change happened ). We get that target name and value. We set that value to a particular state by name.

This way, we managed to have only one event listener for many fields in Form. In ReactJS project, you should use this technique in form.

Conclusion

In this section, we learned about forms in ReactJS.
In the next section, you will learn about how to add validation in Forms in ReactJS.