React Js

React Forms

Forms are very useful in any web application. Unlike angular and angularjs, that gives form validation out of the box. You have to handle forms yourself in React. This brought about many complications like how to get form values, how do I manage form state, how do I validate my form on the fly and show validation messages. There are different methods and libraries out there to help with this but if you are like me that hates dependent on too many libraries, welcome on board, We are going to bootstrap our own form from the ground up.

There are mainly two types of form input in React.

  1. Uncontrolled component
  2. Controlled component

Uncontrolled component

The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM.

Example

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

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 Company Name successfully.');  
      event.preventDefault();  
  }  
  render() {  
    return (  
      <form onSubmit={this.updateSubmit}>  
        <h1>Uncontrolled Form Example</h1>  
        <label>Name:  
            <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 screen.

Controlled Components

In simple HTML elements like input tag, the value of the input field is changed whenever the user type. But, In React, whatever the value user types we save it in state and pass the same value to the input tag as its value, so here its value is not changed by DOM, it is controlled by react state. This may sound complicated But let’s understand with an example.

import React from 'react'; 
import ReactDOM from 'react-dom'; 
   
class App extends React.Component { 
     
    onInputChange(event) { 
        console.log(event.target.value); 
    } 
     
    render() { 
        return ( 
            <div> 
                <form> 
                    <label>Enter text</label> 
                    <input type="text"
                        onChange={this.onInputChange}/> 
                </form> 
            </div> 
        ); 
    } 
} 
export default App;  

In the above example, the input element is uncontrolled whatever the value user type is in the DOM. We are logging that value on the console by getting it from the DOM and the method onInputChange will be called any time user type in anything so the value will be printed on the console every time (Ctrl + Shift + F11) google chrome user to open the console.

React is used to handle the value of user enters.

import React from 'react'; 
import ReactDOM from 'react-dom'; 
   
class App extends React.Component { 
     
    state = { inputValue: '' }; 
     
    render() { 
        return ( 
        <div> 
            <form> 
                <label> Enter text </label> 
                <input type="text"
                    value={this.state.inputValue} 
                    onChange={(e) => this.setState( 
                    { inputValue: e.target.value })}/> 
            </form> 
            <br/> 
            <div> 
                Entered Value: {this.state.inputValue} 
            </div> 
        </div> 
        ); 
    } 
}  
export default App;  

What will happening in the above react example, when we have made inputValue state with value null, and the value of that state is provided to the input field which means whatever the value of the inputValue is we will see it in the input box. And we are updating the value of inputValue each time user changing the value in the input by calling setState() function and dom is re-rendering because we are changing the value of inputValue using setState(). Here, we can easily get the value whatever user type in the input field and pass it to wherever we want from React state. The same happens with other elements like the text area and select. Here is another example that prevents the browser from automatically submitting the form.

import React from 'react'; 
import ReactDOM from 'react-dom'; 
   
class App extends React.Component { 
     
    state = { inputValue: '' }; 
   
    onFormSubmit = (event) => { 
        event.preventDefault(); 
        this.setState({ inputValue: 'Hello World!'}); 
    } 
     
    render() { 
     
        return ( 
        <div> 
            <form onSubmit={this.onFormSubmit}> 
                <label> Enter text </label> 
                <input type="text"
                value={this.state.inputValue} 
                onChange={(e) => this.setState( 
                { inputValue: e.target.value })}/> 
            </form> 
            <br/> 
            <div> 
                Entered Value: {this.state.inputValue} 
            </div> 
        </div> 
        ); 
    } 
} 
export default App;  

Here we just add onSubmit event handler which calls the function onFormSumbit and performs the action of replacing the value of inputValue to ‘Hello World!’, and the preventDefault() function is used to prevent the browser from submitting the form and reloading the page.

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

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

Check Also
Close
Back to top button