Header Responsive Ads

React Form

reactjs form

Form is used to get input data from user. It contains different input fields like textbox, dropdown list, textarea, radiobutton, checkbox etc. React handles HTML form a little bit differently.

In this article, you will learn


Types of React Components

There are two types of react component in respect of handling form data, controlled component and uncontrolled component.

Controlled Component

In controlled component, form data is handled by React component. In component, state is used to store form input data. One state variable keeps data of one input. Event handler update state variable value based on user input typed in textbox. Every time user change value in textbox, event handler is fired and change respective state variable value using setState method. React recommends controlled component.

Uncontrolled Component

Uncontrolled component is like traditional way of handling HTML form input data. In this, form data is stored in DOM, not in component so you can retrieve form data directly from DOM using ref. Here event handler is not needed. Ref gives us access to DOM elements.


Create form in React

In below example, we create a class component which return a simple form. Form contains an input text field to get user name. A state variable is defined in constructor to store name.

import React, {Component} from 'react';
export default class App extends Component{
    constructor(){
        super();
        this.state = {
            name: ''
        };
    }
    render(){
        return(           
            <form>
                <h1>Welcome</h1>
                <input type='text' />
            </form>
        );
    }
}

Change Component State

Now we will write onChange event on input field. When user type in input textbox, onChange reactjs event handler is invoked and change state according to user input as below:-

import React, {Component} from 'react';
export default class App extends Component{
    constructor(){
        super();
        this.state = {
            name: ''
        };
    }
    handleChange = (event=> {
        this.setState({
            name: event.target.value
        })
    }
    render(){
        return(           
            <form>
                <h1>Welcome, {this.state.name}</h1>
                <input 
                    type='text' 
                    onChange={this.handleChange} 
                />
            </form>
        );
    }
}

Submit Form

Now we will attach onSubmit event with form and will write form submit event handler. We have a button to submit form. To prevent the form actual submission, we will write method event.preventDefault().

import React, {Component} from 'react';
export default class App extends Component{
    constructor(){
        super();
        this.state = {
            name: ''
        };
    }
    handleChange = (event=> {
        this.setState({
            name: event.target.value
        })
    }
    handleSubmit = (event=> {
        event.preventDefault();
        alert('Form submitting');
    }
    render(){ 
        return(           
            <form onSubmit={this.handleSubmit}>
                <h1>Welcome, {this.state.name}</h1>
                <input           type='text'           onChange={this.handleChange}           />
                <button type='submit'>
                    Submit
            </button>
            </form>
        );
    }
}

Multiple Inputs

We can have one event handler for multiple inputs. Now we will write another input field for age with onChange event. Make sure that both inputs should contain property name with value same as state variable name. For name, it is name and for age, it is age.

import React, {Component} from 'react';
export default class App extends Component{
    constructor(){
        super();
        this.state = {
            name: 'User',
            age: 20
        };
    }
    handleChange = (event=> {
        let n = event.target.name;
        let v = event.target.value;
        this.setState({
            [n]: v
        })
    }
    handleSubmit = (event=> {
        event.preventDefault();
        alert('Form submitting');
    }
    render(){ 
        return(           
            <form onSubmit={this.handleSubmit}>
                <h1>Welcome, 
                    {this.state.name} 
                    {this.state.age}
                </h1>
                <input           type='text' 
                       name='name'          onChange={this.handleChange}       />
                <input           type='text'           name='age'           onChange={this.handleChange}       />
                <button type='submit'>Submit</button>
            </form>
        );
    }
}

React Form Validation

You can validate user input before form submitting. We will validate input field age as it can only get numbers from user. For this we will write if statement in change event handler.

handleChange = (event=> {

    let n = event.target.name;
    let v = event.target.value;
    if(n == 'age' && !Number(v)){
        alert('Only digits');
    }
    this.setState({
        [n]: v
    })
}

Other Form Input elements

Following are other form input elements

  • Textarea
  • Select (drop down list)
  • Reactjs Radio button
  • Reactjs Check box
  • Input file
  • Input number

<form onSubmit={this.handleSubmit}>
    <h1>Welcome, 
        {this.state.name} 
        {this.state.age}
    </h1>
    <input 
        type='text' 
        name='name' 
        onChange={this.handleChange} 
    />
    <input 
        type='text' 
        name='age' 
        onChange={this.handleChange} 
    />
    <textarea 
        value='this is textarea' 
    />
    <select>
        <option value='france'>
            France
        </option>
        <option value='usa' selected>
            USA
        </option>
        <option value='canada'>
            Canada
        </option>
    </select>
    <input 
        type='radio' 
        value='Male' 
        name='gender' 
    />Male
    <input 
        type='radio' 
        value='Female' 
        name='gender' 
    />Female
    <input type='file'  />
    <input type='checkbox' />Remember Me
    <input type='number' />
    <button type='submit'>
        Submit
    </button>
</form>



Post a Comment

Previous Post Next Post