Whether you are a front-end developer or back-end engineer, forms are something you can’t ignore. Forms look simple and easy, but there are a few complications involved behind every form, like how to validate the value of a form input, how to stop a user from entering an invalid value, or how to show the validation message on the fly, and so on.

How to create and handle forms in React

JS frameworks make your life much easier when it comes to forms, as they are provided to you with form validation out of the box. But for some weird reason, React wants us to handle forms ourselves.

In this lesson, you are going to learn about React forms in detail. Before diving into the examples, let me give you a brief introduction of the types of form input in React.

React has two different types of form inputs

  1. Controlled Components – These are defined with a value property.
  2. Uncontrolled Components – These do not have a value property.

Controlled Components

In HTML, form elements such as <input>, <textarea>, <select> maintain their state and update it as per the user’s input. In React, the state property of a component can be updated with only setState().

The value of the input element is controlled by React so the component and the input value of the form element in synchronization all the time. Even if the user enters a value in the input, it will not have any direct influence on the rendered input. As the value changes, the component will save the value in its state.

Example:

Let’s create a simple form with two elements: An input field for the userName and a submit button.
To create a form element, use the basic template to create a class-based component.

import React from 'react'
import ReactDOM from 'react-dom'
class App extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            //html form in JSX goes here
        );
    }
} //component end

In the return() method you have to create a form using JSX.
Let’s create a simple form using HTML and then convert it into JSX.

In HTML, the form will be:

<div>
   <form>
      <label for = 'name'>Enter your Name: </label>
      <input id = 'name' type = 'text' value = ''/>
      <input type = 'submit' value= 'submit'/>
   </form>
</div>

In JSX, it will be something like this:

<div>
   <form onSubmit ={this.onSubmit}>
      <label htmlFor='name'>Enter your Name </label>
      <input id='name' onChange={this.onChange} value={this.state.name} />
      <input type='submit' value='submit'/>
   </form>
</div>

Add this.state = { name: '' }; in the constructor() method of the component. It will represent the initial state of the form element, which is empty by default.

Now create two methods to handle the change of the input value and form submission.

onChange(event) {
    this.setState({ name: event.target.value
    });
}
onSubmit(event) {
    console.log(this.state.name);
    event.preventDefault();
}

In the end, bind these two methods in the constructor() method.

this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);

Putting everything together, we will get the following piece of code.

Index.js

import React from 'react'
import ReactDOM from 'react-dom'
class App extends React.Component {
    constructor(props) {
        super(props);
        this.onChange = this.onChange.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
        this.state = {
            name: ''
        };
    }
    onChange(event) {
        this.setState({
            name: event.target.value
        });
    }
    onSubmit(event) {
        console.log(this.state.name);
        event.preventDefault();
    }
    render() {
        return ( <div>
            <form onSubmit = {
                this.onSubmit
            } >
            <label htmlFor = 'name' > Name: </label> 
            <input id = 'name'
            onChange = {
                this.onChange
            }
            value = {
                this.state.name
            }/> 
            <input type = 'submit'
            value = 'submit' />
            </form> 
            </div>
        )
    }

}
ReactDOM.render( < App / > , document.getElementById('root'))

After you click on the submit button, the value of the state will be logged.

Uncontrolled Components

If the component’s internal state and the input value are kept in synchronization by the application instead of the React, it is referred to as an uncontrolled component.

To convert the above component into an uncontrolled component, you have to do the following.

1. Add a new ref property to the input value. Using ref, you can pull the value of the form input.

<input id='name' ref='name' onChange={this.onChange} value={this.state.name}

1. Rewrite your onSubmit() method using this.refs

onSubmit(event) {
    console.dir(this.refs.name.value);
    event.preventDefault();
}

Now, for the sake of practice, create a controlled form component in React that takes your name and prints a greeting message with your name in the console. After you are done, convert it into an uncontrolled component. I hope this lesson did make sense to you. In case, you have any unanswered question from this tutorial, feel free to leave it in the comment section below.

React Event Handling << Tutorial Home >> React and JavaScript

 

Last modified: September 9, 2019

Comments

Write a Reply or Comment

Your email address will not be published.