React Tutorial- How To Store React Form Data Or Store In Local Storage

We will see in this React tutorial how to store React’s form data or form state in local storage using React Life Cycle methods.

Local Storage is quite handy and beneficial in storing the data on the web browser since that data doesn’t disappear from the browser unless we remove the browser’s cache.

We will be creating a basic React app in which we will complete a basic user form using Bootstrap 4. In this form, we can define the name, email and phone number.

Even if we refresh the browser, the React form won’t change at all.

 

Introduction To Web Storage

There are two types of local storage- Web Storage and Session Storage.

 

Local Storage-The data is stored in the browser’s memory and it doesn’t expire even after the browser’s window is closed.

Session Storage– The data exists as long as the browser’s window is not closed.

 

It should be kept in mind that local storage is the best web storage due to its higher storage limit. Given-below are the local storage methods:

Method                                        Description

setItem()                                      Set values in local storage by using key and value

getItem()                                     Get a value by using the key

removeItem()                           Delete an item by using the key

clear()                                          Clears the storage data

 

How To Store React Form data Or State In Local Storage

Step 1- React Local Storage Tutorial With Example

Step 2- Install React v16+ With Example

Step 3- Create React Component

Step 4- Store React Form State In Local Storage With Life Cycle Methods

 

Step 1- React Local Storage Tutorial With Example

We must install the basic React app for the local storage demo.

 

Step 2- Install React v16+ With Bootstrap 4

Fist of all, we have to install the basic React project with Bootstrap 4. Then, we run the given command from our terminal:

npx create-react-app react-local-storage

Further, we will get into the React local storage project by using the given command:

cd react-local-storage

Afterward, we have to install Bootstrap 4 project in React app:

npm install bootstrap --save

Next, we import bootstrap.min.css in the src/App.js file from node_modules folder:

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './App.css';
class App extends Component {
  render() {
    return (
      <div className="App">
        <h3>React Local Storage Tutorial</h3>
      </div>
    );
  }
}
export default App;

Now, we will run the React app:

npm start

 

Step 3- Create React Component

Here, we create src>components folder and create a component file for storing form data in local storage. We will also name this file form-data-component.js and paste the following code in it:

import React, { Component } from 'react';
export default class FormDataComponent extends Component {
    render() {
        return (
            <div className="container">
                <form>
                    <div className="form-group">
                        <label>Name</label>
                        <input type="text" className="form-control" />
                    </div>
                    <div className="form-group">
                        <label>Email</label>
                        <input type="email" className="form-control" />
                    </div>
                    <div className="form-group">
                        <label>Phone</label>
                        <input type="tel" className="form-control" />
                    </div>
                    <button type="submit" class="btn btn-primary btn-block">Submit</button>
                </form>
            </div>
        )
    }
}

We created a basic user form using Bootstrap 4. This tiny form has a name, email and phone number filed.

Next, we add FormDataComponent file in the src/App.js file:

import React, { Component } from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './App.css';
import FormDataComponent from './components/form-data.component';
class App extends Component {
  render() {
    return (
      <div className="App">
        <FormDataComponent />
      </div>
    );
  }
}
export default App;

 

Step 4- Store React Form State In Local Storage With Life Cycle Methods

In this step, we will insert the values in the React form and store those values in the local storage using localStorage web API and ReactJs component life cycle methods.

Now, we need to add the given code in the components/form-data.component.js file:

import React, { Component } from 'react';
export default class FormDataComponent extends Component {
    userData;
    constructor(props) {
        super(props);
        this.onChangeName = this.onChangeName.bind(this);
        this.onChangeEmail = this.onChangeEmail.bind(this);
        this.onChangePhone = this.onChangePhone.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
        this.state = {
            name: '',
            email: '',
            phone: ''
        }
    }
    // Form Events
    onChangeName(e) {
        this.setState({ name: e.target.value })
    }
    onChangeEmail(e) {
        this.setState({ email: e.target.value })
    }
    onChangePhone(e) {
        this.setState({ phone: e.target.value })
    }
    onSubmit(e) {
        e.preventDefault()
        this.setState({
            name: '',
            email: '',
            phone: ''
        })
    }
    // React Life Cycle
    componentDidMount() {
        this.userData = JSON.parse(localStorage.getItem('user'));
        if (localStorage.getItem('user')) {
            this.setState({
                name: this.userData.name,
                email: this.userData.email,
                phone: this.userData.phone
            })
        } else {
            this.setState({
                name: '',
                email: '',
                phone: ''
            })
        }
    }
    componentWillUpdate(nextProps, nextState) {
        localStorage.setItem('user', JSON.stringify(nextState));
    }

    render() {
        return (
            <div className="container">
                <form onSubmit={this.onSubmit}>
                    <div className="form-group">
                        <label>Name</label>
                        <input type="text" className="form-control" value={this.state.name} onChange={this.onChangeName} />
                    </div>
                    <div className="form-group">
                        <label>Email</label>
                        <input type="email" className="form-control" value={this.state.email} onChange={this.onChangeEmail} />
                    </div>
                    <div className="form-group">
                        <label>Phone</label>
                        <input type="tel" className="form-control" value={this.state.phone} onChange={this.onChangePhone} />
                    </div>
                    <button type="submit" className="btn btn-primary btn-block">Submit</button>
                </form>
            </div>
        )
    }
}

 

  • Declare the userData variable. In this variable, we will store the form’s value from local storage.
  • As we can see, we have used the componentDidMount() component life cycle method. This method is best used for defining the state. So, we are setting up the form data in the userData variable and checking if the localStorage exists, then setting up the form state via local storage.
  • The componentWillUpdate() method triggers before the rendering  happens. We are setting up form state in local storage.
  • In the HTML input field, we define the onChange=”” event with specific methods. These methods will trigger when the value of the field is being changed. We also pass the value and giving the value using the this.state.

if we enter the value in the React form, then we can check out the user object in browser’s local storage tab. When we refresh or close the browser window, even then we won’t lose the form state.

 

Conclusion

in this React tutorial, we learned how to store form data or store in local storage using React life cycle methods. Hope that all have understood about local storage to React and using life cycle methods along with that.

 

Thanks

Leave a Reply

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