How to create Forms in React Js

Forms are an important part of React applications. They allow us to take information from the users and save them. They make our application really interactive. There are two ways of implementing react forms. First, when the form data is handled by the React Component. This approach is called the controlled component. Second, when we allow the browser itself to handle the data. This approach is called an uncontrolled component as it is managed by the DOM. It is preferred to use the controlled component in our applications.

Creating Forms in React JS

Let’s create a simple form in React JS. We will use the form tag. Inside of it, we will use two input elements surrounded by label elements to give a proper label for each input. Note that the input element’s id attribute should match the label element’s for attribute. This keeps them linked together. We will wrap this whole thing inside the fieldset element. It will give a boundary to our form. The app.js should look like this:

import React, { Component } from 'react'

class App extends Component {
 
  render() {
    return (
      <form>
        <fieldset>
          <label for="name">Enter your name: </label>
          <input type="text" id="name" /><br/><br/>
          <label for="age">Enter your age: </label>
          <input type="number" id="age" min='1'/><br/><br/>
          <button>Submit</button>
        </fieldset>
      </form>
    )
  }
}

export default App

The output would look like this:

If we type anything and click on the submit button, the page refreshes. We obviously don’t want this. We want our entered data to be saved otherwise what will be the use of this form. So to save our data we will use state.

We will create two state variables- name and age. Add the name attribute to the input element. This will help React to classify which state variable to update based on their names. We will create two functions- handleChange() and handleSubmit(). To control the changes, we will have to use event listeners- onChange and onSubmit. This is the advantage of React forms. We can control our data. Our code should look like this now:

import React, { Component } from 'react'

class App extends Component {
  constructor(props){
    super(props);
    this.state={name:'',age:0};
  }
  handleSubmit=()=>{

  }
  handleChange=()=>{

  }
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <fieldset>
          <label for="name">Enter your name: </label>
          <input type="text" id="name" 
                  name="name"
                  onChange={this.handleChange} /><br/><br/>
          <label for="age">Enter your age: </label>
          <input type="number" id="age" min='1' 
                  name="age"
                  onChange={this.handleChange}/><br/><br/>
          <button>Submit</button>
        </fieldset>
      </form>
    )
  }
}
export default App

This would not make any difference since our functions are empty. We will use setState inside handleChange to update the state. Following which we will print the data using alert. The code will look like this:

import React, { Component } from 'react'

class App extends Component {
  constructor(props){
    super(props);
    this.state={name:'',age:0};
  }
  handleSubmit=(e)=>{
    alert('Your name is: '+this.state.name +'\nYour age is: '+this.state.age);
    e.preventDefault();
  }
  handleChange=(e)=>{
    const name=e.target.name;
    this.setState({
      [name]:e.target.value
    });
  }
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <fieldset>
          <label for="name">Enter your name: </label>
          <input type="text" id="name" 
                  name="name"
                  onChange={this.handleChange} /><br/><br/>
          <label for="age">Enter your age: </label>
          <input type="number" id="age" min='1' 
                  name="age"
                  onChange={this.handleChange}/><br/><br/>
          <button>Submit</button>
        </fieldset>
      </form>
    )
  }
}
export default App

You can see, in line no. 13, we are storing the event.target.name value in the name variable. This name variable contains either name or age. In line no.15, the name’s value gets updated. So with one function, we handled two input elements. Using alert, we print the name and age entered. Line 10 prevents our data from being deleted.

The output will look like this:

Conclusion:

We can store the data using React Components and state. This data would be available within the entire class. We can send this data to the client-side and save it for future use. This is how React forms works. In conclusion, it makes the process of handling data very efficient. You can go through theĀ official documentation for more examples.

Leave a Reply

Your email address will not be published. Required fields are marked *