React JS from

React JS

Form is an important component for any application that for the interaction with the user. Lets say, forms are the only way for receiving feedback & suggestion, user inputs and other inputs from the user. Same goes for the React JS applications. React JS recommends using controlled components to implement forms. Form data is handled by a React component in controlled component. The alternative is uncontrolled components, where form data is handled by the DOM itself. So here we are going to create a working React JS form.

Project Setup

First we’ll setup our react js project with create-react-app.

create-react-app example-form-app
cd example-form-app

This will create our project folder ‘example-form-app‘ with all the essential files and folder structure and dependency packages that we need to build our app. The project folder layout will look something like this.

example-form-app/
  README.md
  node_modules/
  package.json
  .gitignore
  public/
    favicon.ico
    index.html
  src/
    App.css
    App.js
    App.test.js
    index.css
    index.js
    logo.svg

To run the app, run npm start command, which runs our app in development mode. Open http://localhost:3000 to view in browser.

npm start

React JS form building

Now lest start building our form. We will be creating a simple form to get user details that will include name, address, email, phone, gender and marital status.

For that, we fill first replace default content of App.js file inside src/ folder with the following content.

import React from 'react';
import './App.css';
import Form from "./components/Form";

function App() {
    return (
        <div className="App">
            <header>
                <h1>User Details</h1>
            </header>
            <section>
            </section>
        </div>
    );
}

export default App;

Now we will create the form component to build the form that user will fillup. For that, we create a new folder called components (or anything you like) inside the src/ folder. We will define all our components inside this directory.

cd src/
mkdir components

Now we’ll create form component with the fields we mentioned above.

import React, {Component} from 'react';

class Form extends Component {

    constructor(props) {
        super(props);
        this.state = {}
    }

render(){
return <div className="container">
                <form></form>
</div>
}
}
export default Form;

Now we’ll add the form fields.

<form>
                    <label>Name </label>
                    <input type={'text'}
                           name={'name'}/>

                    <br/>

                    <label>Email </label>
                    <input type={'text'}
                           name={'email'}/>

                    <br/>

                    <label>Phone </label>
                    <input type={'tel'}
                           name={'phone'}/>

                    <br/>

                    <label>Address</label>
                    <textarea name={'address'}/>

                    <br/>

                    <label>Gender </label>
                    <select name={'gender'}>
                        <option value={'M'}>Male</option>
                        <option value={'F'}>Female</option>
                        <option value={'O'}>Other</option>
                    </select>


                    <br/>

                    <label>Married</label>
                    <input type={'checkbox'}
                           name={'married'}/>

<br/>
<button>Submit</button>
</form>

Here we will using controlled component to implement form. React JS virtual DOM handles the form fields . We can implement controlled component as below.

Form handling

First we set a form state variable along with the form fields we have in our form. in the constructor section, we add

this.state = {
form:{
name:'',
email:'',
address:'',
pone:'',
married:false,
gander:''
}
}

Now to reflect the changes in the controller form component while filling up the form, we will set the value of the form fields form the form state we defined above. For this, we need a method to handle the change in the form and update it in the form state. We define that method as

handleOnchange = (e) => {
        let form = this.state.form
        if (e.target.type === 'checkbox')
            if (e.target.checked) {
                form[e.target.name] = true
            } else {
                form[e.target.name] = false
            }
        else
            form[e.target.name] = e.target.value
        this.setState({
            form
        })
    }

Now we will call above method whenever user makes any change in the form component. We will capture the change event and update the form state accordingly.

Input textbox
// onChange={e => this.handleOnchange(e)}
 <input type={'text'}
                           value={this.state.form.name}
                           onChange={e => this.handleOnchange(e)}
                           name={'name'}/>
Checkbox
<input type={'checkbox'}
       onChange={e => this.handleOnchange(e)}
       checked={this.state.form.married ? 'checked' : ''}
       name={'married'}/>
Select Box
<select name={'gender'}
                            defaultValue={this.state.form.gender}
                            onChange={e => this.handleOnchange(e)}>
                        <option value={'M'}>Male</option>
                        <option value={'F'}>Female</option>
                        <option value={'O'}>Other</option>
                    </select>

Now any changes user makes in the form component is saved in the state.

Finally we need to submit the form to the API to save the form input. To submit the form, we ill define a method that will be called on form submission and handle the further process like posting form input to the API. We will be posting the form state data rather than the form itself.

handleSubmit = (e) => {
        e.preventDefault()
        console.log(this.state.form)
// futher logic to post the form data to API
// postToAPI(this.state.form)
    }

And in form component,

<form onSubmit={this.handleSubmit}>
...
</form>

Thus, we just created a controlled component form that user can fill and submit. This is just the basic form submission process. We can add validation and other rules and logic as per the need.

The complete code repo is available in Github

You May Also Like