How to use localStorage with React

    Oct 07, 2019       by Suraj Roy
/localstorage-in-reactjs-app.jpg

For a long time, cookies were the main way to store information at the browser(client side). They were used to record stateful elements like shopping cart items or options changed by a user. They were also used to remember user browsing habits or to keep a user logged in while they went from page to page. Then, HTML5 appeared on the scene and introduced LocalStorage as another data storage option. This new Javascript object (along with SessionStorage) boasted a much large storage capacity than cookies at a whopping 5MB.

 

In this article, I will create a sample application to show how to use localStorage in the Reactjs application. localStorge is one of the easiest ways to store data at client-side and the best thing about local storage is that data doesn’t remove from the browser unless we remove the browser’s cache. 

 

I will create a basic React app, in which there will be a basic user form using Bootstrap 4. In this form, I will define the  title, description, and price of a document. ere with the help of localStorage, the React form state won’t change after the page refresh. we will use the React life cycle methods to set the Form state in local storage.

 

Let's Get Started 

Step 1: Create new react app and install bootstrap package

Create new application over terminal:

npx create-react-app local-storage-reactjs

 

Now, move to project folder and install bootstrap 4

npm install bootstrap --save

 

Add the below file path at the top of App.js file inside src folder.

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

 

Step 2: Create a new component and save form data in localStorage using Life cycle methods.

Create new component components/AddDocument.js and put below code inside it. In this component, we will see how to save data in localStorage using Life cycle methods.

 

 
import React, { Component } from 'react';
 
export default class AddDocumentComponent extends Component {
    documentData;
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
        this.handleFormSubmit = this.handleFormSubmit.bind(this);
        this.state = {
            title: '',
            description: '',
            price: ''
        }
    }
 
handleChange= (e)=> {
    this.setState({[e.target.name]:e.target.value});
}
// on form submit...
handleFormSubmit(e) {
    e.preventDefault()
   localStorage.setItem('document',JSON.stringify(this.state));
}
 
// React Life Cycle
componentDidMount() {
    this.documentData = JSON.parse(localStorage.getItem('document'));
 
    if (localStorage.getItem('document')) {
        this.setState({
            title: this.documentData.title,
           description: this.documentData.description,
           price: this.documentData.price
    })
} else {
    this.setState({
        title: '',
        description: '',
        price: ''
    })
}
}
 
render() {
    return (
        <div className="container">
            <form onSubmit={this.handleFormSubmit}>
                <div className="form-group">
                    <label>Title</label>
                    <input type="text" name="title" className="form-control" value={this.state.title} onChange={this.handleChange} />
                </div>
                <div className="form-group">
                    <label>Description</label>
                    <input type="text" name="description" className="form-control" value={this.state.description} onChange={this.handleChange} />
                </div>
                <div className="form-group">
                    <label>Price</label>
                    <input type="number" name="price" className="form-control" value={this.state.price} onChange={this.handleChange} />
                </div>
                <button type="submit" className="btn btn-primary btn-block">Submit</button>
            </form>
        </div>
    )
}
}
 

 

In the above code, Following task has been done:

  • Declared a variable documentData, in this variable we will store the form’s value from local storage.
  • Below that, we used the componentDidMount() component life cycle method, to load data in state from localStorage in case of page refresh.
  • Defined handleFormSubmit  method which is called on form submit, In this method data is stored in localStorage.

These are the main tasks done for the storage of data in localStorage.

 

Step 3: Run the app

 

Run app from the terminal, 

npm start

App will run on  browser like below:

localstorge reactjs app

 

Conclusion

In this article, I explained how to use localStorage to store form or state data in Reactjs application.

You can also find other demos of React.js Sample Projects here to start working on the enterprise-level applications.

That’s all for now. Thank you for reading and I hope this demo will be very helpful for using localStorage with Reactjs form  application.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.

Thank you!

You can download complete code from here. Download Code


WHAT'S NEW

Find other similar Articles here: