Home >>ReactJS Tutorial >ReactJS Forms

ReactJS Forms

ReactJS Forms

Forms are simply a part of every modern web application. It allows the users to interact with the application as well as collect user information. Forms can perform a lot of tasks depending on the complexity of your business needs and logic, such as user authentication, user inserting, searching, filtering, booking, ordering etc. A form may contain text fields, checkbox ,buttons, button Radio, etc.

Creating Form

React provides a stately, reactive approach to form-building. The component normally handles the React form, rather than the DOM. The type is normally implemented in React with the use of controlled components.

  1. Uncontrolled component
  2. Controlled component

Uncontrolled component

Uncontrolled input is similar to traditional inputs in the HTML-form. The DOM handles the data concerning the form itself. Here, when the input value changes, the HTML elements preserve their own state, which will be updated. You need to use a ref to write an uncontrolled part to get type values from the DOM. In other words, for each state update no need to write an event handler. Use a refer to access the form 's input field value from the DOM.

Example

In this example, the code accepts an uncontrolled component with a field username and company name.


import React, { Component } from 'react';  
class App extends React.Component {  
  constructor(props) {  
      super(props);  
      this.updateSubmit = this.updateSubmit.bind(this);  
      this.input = React.createRef();  
  }  
  updateSubmit(event) {  
      alert('You have entered the UserName and CompanyName successfully.');  
      event.preventDefault();  
  }  
  render() {  
    return (  
      <form onSubmit={this.updateSubmit}>  
        <h1>Example1</h1>  
        <label>Username:  
            <input type="text" ref={this.input} />  
        </label>  
        <label>  
            CompanyName:  
            <input type="text" ref={this.input} />  
        </label>  
        <input type="submit" value="Submit" />  
      </form>  
    );  
  }  
}  
export default App;  

Output:-

When you execute the above code, you will see the following Output on the screen

reactjs Forms

Controlled Component

Throughout HTML, usually form elements retain their own state and update it according to the user input. In the controlled component, the component handles the input form element instead of the DOM. Here the mutable state is held in the state property and can only be updated with the method setState().

Controlled components have functions that govern the data that is passed on to them at each onChange event, rather than only collecting information once, e.g. when you click a submit button. These data are then saved to state and updated with the method setState(). This makes the component even more control of the elements and data of the form.

A controlled component takes its current value through props and notifies the changes like a onChange event via callbacks. A parent component "controls" this by handling the callback and controlling its own state, and then transferring the new values to the controlled component as props. It's called a "dumb component," too.

Example
Output:-

When you execute the above code, you will see the following Output on the screen.

reactjs Forms

Handling Multiple Inputs in Controlled Component

If multiple managed input elements are to be handled, add a name attribute to each element and then the handler function decides what to do based on the event.target.name value.

Example

import React, { Component } from 'react';  
class App extends React.Component {  
    constructor(props) {  
        super(props);  
        this.state = {  
            personGoing: true,  
            numberOfPersons: 5  
        };  
        this.handleInputChange = this.handleInputChange.bind(this);  
   }  
   handleInputChange(event) {  
       const target = event.target;  
       const value = target.type === 'checkbox' ? target.checked : target.value;  
       const name = target.name;  
       this.setState({  
           [name]: value  
       });  
  }  
  render() {  
      return (  
          <form>  
              <h1>Example 3</h1>  
              <label>  
                  checkbox:  
                  <input  
                    name="personGoing"  
                    type="checkbox"  
                    checked={this.state.personGoing}  
                    onChange={this.handleInputChange} />  
             </label>  
             <br />  
             <label>  
                 Total Number:  
                 <input  
                 name="numberOfPersons"  
                 type="number"  
                 value={this.state.numberOfPersons}  
                 onChange={this.handleInputChange} />  
             </label>  
         </form>  
     );  
  }  
}  
export default App;  

Output:-

reactjs Forms


No Sidebar ads