React Local Storage Tutorial: Store Form State in localStorage

React local storage tutorial; In this quick guide, we will inevitably ascertain how to store form data in the browser’s local storage within React application. Additionally, you will learn how to quickly set up local storage and store state in local storage.

Gone are the days of cookies; we still remember cookies were popular to store client-side information, especially on the user’s browsers. However, since the invocation of HTML 5, the entire game changed drastically; HTML 5 brought local storage, which transformed the way we used to store data on the client-side.

JavaScript’s local storage mechanism has made the whole development experience commemorative. The localStorage object allows you to store data on the browser, and data saves in key/value pair in a web browser with no expiration date.

The quintessential thing about local storage is that data doesn’t get deleted from the browser no matter if you close the browser, come next, day, week, month or year.

This post will show you how to create a basic react app using the command-line tool to create a reusable form component using the bootstrap package. We will add a name, email, contact number, and message form input properties; theoretically, you will learn how to save form data in local storage in react environment.

How to Store Data in Local Storage with React

  • Step 1: Install React Project
  • Step 2: Add Bootstrap in React
  • Step 3: Create Reusable Form Component
  • Step 4: Update App.js
  • Step 5: React Store Contact Form Data in localStorage
  • Step 6: Start React Application

Install React Project

The first instruction you have to follow, head over to the terminal, open the command prompt, type the following command. Further execution of command commences the react app installation process.

If this step seems needless to you, please move to the second step.

npx create-react-app react-blog-app

Step inside the project.

cd react-blog-app

Add Bootstrap in React

HTML and CSS are the handy languages that give us the power to create any web page and the ui elements, but it takes time. Hence, you can use the bootstrap library to create the ui elements rapidly; it is easy to install the bootstrap plugin;

Consequently, make sure to invoke the given command.

npm install bootstrap

Create Reusable Form Component

Create components directory inside the src folder, plus create the contact_form.component.js file, then update the given below code in the src/components/contact_form.component.js.

Update App.js

In the subsequent step, you have to open the main app js file, in this file you require to add the contact form component.

So, open and update the main src/App.js file.


import React from 'react';

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './App.css';

import ContactFormComponent from './components/contact_form.component';


function App() {
  return (
    <div className="App">
      <div className="container mt-5">
        <ContactFormComponent/>
      </div>
    </div>
  );
}

export default App;

React Store Contact Form Data in localStorage

Next, we have to open code in the components/contact_form.component.js and update the following code.

import React, { Component } from 'react';

export default class ContactFormComponent extends Component {

    DATA;

    constructor(props) {
        super(props);

        this.eventName = this.eventName.bind(this);
        this.eventEmail = this.eventEmail.bind(this);
        this.eventContact = this.eventContact.bind(this);
        this.eventMessage = this.eventMessage.bind(this);

        this.onFormSubmit = this.onFormSubmit.bind(this);

        this.state = {
            name: '',
            email: '',
            contact: '',
            message: ''
        }
    }

    // Event handlers
    eventName(event) {
        this.setState({ name: event.target.value })
    }

    eventEmail(event) {
        this.setState({ email: event.target.value })
    }

    eventContact(event) {
        this.setState({ contact: event.target.value })
    }

    eventMessage(event) {
      this.setState({ message: event.target.value })
    }    

    onFormSubmit(event) {
      event.preventDefault()
    }


    componentDidMount() {
        this.DATA = JSON.parse(localStorage.getItem('contact_form'));

        if (localStorage.getItem('contact_form')) {
            this.setState({
                name: this.DATA.name,
                email: this.DATA.email,
                contact: this.DATA.contact,
                message: this.DATA.message
            })
        } else {
            this.setState({
                name: '',
                email: '',
                contact: '',
                message: ''
            })
        }
    }

    componentWillUpdate(nextProps, nextState) {
        localStorage.setItem('contact_form', JSON.stringify(nextState));
    }

    render() {
        return (
            <div className="container">
                 <div className="card">
                     <div className="card-body">
                        <form onSubmit={this.onFormSubmit}>
                            <div className="form-group mb-3">
                                <label><strong>Name</strong></label>
                                <input type="text" className="form-control" value={this.state.name} onChange={this.eventName} />
                            </div>
                            <div className="form-group mb-3">
                                <label><strong>Email</strong></label>
                                <input type="email" className="form-control" value={this.state.email} onChange={this.eventEmail} />
                            </div>
                            <div className="form-group mb-3">
                                <label><strong>Contact</strong></label>
                                <input type="text" className="form-control" value={this.state.contact} onChange={this.eventContact} />
                            </div>
                            <div className="form-group mb-3">
                                <label><strong>Message</strong></label>
                                <textarea className="form-control" value={this.state.message} onChange={this.eventMessage} />
                            </div>
                            <div className="d-grid mt-3">
                                <button type="submit" className="btn btn-primary btn-block">Submit</button>
                            </div>
                        </form>
                      </div>
                  </div>
            </div>
        )
    }
}

The bootstrap is helping us here to build the form using its form control module.

The event handlers are essential in react to call or trigger any DOM event. We are using the onChange event handler to track the input field values, which we defined as state, we can also use it to get in the local Storage.

The componentDidMount() is called instantly after a component is mounted. Generically, this method is beign used to set the form state.

The onFormSubmit method is evoked after the form is submitted, we will set the form data in localStorage.

The componentWillUpdate() offers you privilege to manipulate the component just before it accepts new props or state. This trait force us to use it to set the form state in local storage.

Start React Application

The tutorial is almost finalized, now we have to run the app.

npm start

Here is the final url, you can use it to view and test the app.

http://localhost:3000

localStorage in React

Conclusion

The tutorial is completed, we have revealed how to save form data or form state in localStorage exclusively in the Reactjs app. We hope this guide will become helpful to you and help understand you react a little better.