What is localStorage?
The localStorage is a Web API available to all modern web browsers by default. It allows websites to store a minimal amount of data in the browser which can be used in future browser sessions. localStorage is similar to sessionStorage except that the localStorage does not have an expiration date.
Advantages of localStorage
- Can store a large amount of data compared to cookie-based storage of data (typically 2MB – 10MB)
- Data persists in the browser to be used across future browser sessions as long as the same protocol on the domain is being used.
- Data need not be passed with each req and res objects.
Why localStorage?
- Experiment with a fake back end when the network connection is poor.
- Saving some default data across sessions like form data ( first name, address, etc) when it needs to be filled multiple times.
Syntax:
window.localStorage // It returns a Storage Object
Methods of localStorage:
- setItem(key, value): Used to save data to localStorage.
- removeItem(key): Used to remove data from localStorage.
- getItem(key): It read data from localStorage.
- clear(): It clears localStorage (on the domain).
Syntax to save data to localStorage:
localStorage.setItem(key, value) Ex: localStorage.setItem("firstName", "Mark Zuker berg");
Syntax to read data from localStorage:
localStorage.getItem(key) // Returns the string "Mark Zuker berg" Ex: localStorage.getItem("firstName");
Syntax to remove data from localStorage:
localStorage.removeItem(key) Ex: localStorage.removeItem("firstName");
We have learned the required basics about localStorage. Let’s implement the above methods with an example.
Prerequisites:
- Basic knowledge of React.
- Any code Editor.
Example: We will implement a small image posting platform called Pics Villa, with two web pages:
1. Post form: Takes the input from the user. It takes the following input:
- Post Title: The title for our post and is of string type.
- Image URL: URL of the image. It can be the public link of the image stored in Google cloud or any other service of your choice. However, for this example, all the images are uploaded to Github and the link to download is used. In this case, the image url may look something like the following format: https://raw.githubusercontent.com/<your username>/<your repo name>/<actual-image-path>
- Post Comment: It is a multi-line string.
2. All Posts: Displays the form data entered by the User.
Steps to create your application:
1. Create your application using the following command:
npx create-react-app crud-application
2. The above command creates a React project for us with all the required boilerplate. Let’s enter into the src folder of the project by typing the below command:
cd crud-application/src
3. You can remove some unnecessary files (Optional step):
rm App.css App.test.js logo.svg
4. To allow routing of web pages. Install the following module:
npm i react-router-dom
5. Check your package.json to match the following dependencies:
"dependencies": { ....................... "react": "^17.0.1", "react-dom": "^17.0.1", "react-router-dom": "^5.2.0", "react-scripts": "4.0.1", "web-vitals": "^0.2.4", ..................... // Other dependencies (if any) },
Filename: App.js
Javascript
import React, { Component } from 'react' ; import { BrowserRouter, Route, Switch } from 'react-router-dom' ; import PostForm from './PostForm' ; import AllPost from './AllPost' ; class App extends Component { render() { return ( <div className= "App" > <BrowserRouter> <Switch> <Route exact path = '/' render= {props => <PostForm {...props} />}> </Route> <Route exact path= '/gallery' render= {props => <AllPost {...props} />}> </Route> </Switch> </BrowserRouter> </div> ); } } export default App; |
Filename: Index.js
Javascript
import React from 'react' ; import ReactDOM from 'react-dom' ; import './index.css' ; import App from './App' ; ReactDOM.render(<App /> , document.getElementById( 'root' )); |
Filename: PostForm.js
Javascript
import React, { Component } from 'react' ; import { Link } from 'react-router-dom' ; const galleryStyle ={ border: 'none' , margin: 0, color: '#fff' , fontWeight: 'bold' , padding: '16px 20px' , position: 'absolute' , top: '35px' , right: '200px' , background: '#7bc74d' , } const postBtnStyle = { border: 'none' , margin: 0, color: '#fff' , fontWeight: 'bold' , padding: '16px 20px' , background: '#7D4C92 ' , width: '417px' , } const parentDiv = { align: 'center' , margin: '0px auto auto auto' , textAlign: 'center' , } const formStyle = { width: '400px' , border: '1px solid lightgray' , margin: '10px auto 10px auto' , textAlign: 'center' , padding: '30px 40px 30px 40px' , } const inputFields = { width: 'inherit' , fontFamily: 'arial' , padding: '6px' , } class PostForm extends Component { handleSubmit = (e) => { e.preventDefault(); const title = this .getTitle.value; const message = this .getMessage.value; const image = this .getImage.value; localStorage.setItem( 'title' , title); localStorage.setItem( 'message' , message); localStorage.setItem( 'image' , image); this .getTitle.value= '' ; this .getMessage.value = '' ; this .getImage.value = '' ; } render() { return ( <div style={parentDiv}> <h1 style={{color: '#8A2482' }}>Pics <span style={{color: '#248A6E' }}>Villa</span> </h1> <p>One place stop for all kinds of images</p> <hr></hr> <h3>Create a new Post</h3> <form onSubmit={ this .handleSubmit} style={formStyle}> <input style={inputFields} required type= "text" placeholder= "Enter Post Title" ref={(input)=> this .getTitle = input } /><br /><br /> <input style={inputFields} required type= "text" placeholder= "Paste your image url here" ref={(input) => this .getImage = input} /><br></br> <br></br> <textarea style={inputFields} required rows= "5" cols= "28" placeholder= "Enter Comment" ref={(input)=> this .getMessage = input}/> <br /><br /> <button style={postBtnStyle}>Post</button> </form> <Link to= '/gallery' > <button style={galleryStyle}> View Gallery </button> </Link> </div> ); } } export default PostForm; |
Filename: AllPost.js
Javascript
import React, { Component } from 'react' ; import Post from './Post' ; const parentDiv = { align: 'center' , margin: '0px auto auto auto' , textAlign: 'center' , } class AllPost extends Component { render() { return ( <div style={parentDiv}> <h1 style={{color: '#8A2482' }}>Pics <span style={{color: '#248A6E' }}>Villa</span> </h1> <p>One place stop for all kinds of images</p> <hr></hr> <h1>All Posts</h1> <Post/> </div> ); } } export default AllPost; |
Filename: Post.js
Javascript
import React, { Component } from 'react' ; class Post extends Component { render() { return ( <div style={{ width: '50%' , margin: '0px auto' }} > <h2>{localStorage.getItem( 'title' )}</h2> <img src={localStorage.getItem( 'image' )} alt={ 'C - language' } /> <p style={{width: '50%' , margin: '0px auto' }} >{localStorage.getItem( 'message' )}</p> </div> ); } } export default Post; |
Run the application using the following command:
npm start
After the server is started, you will see the following output on your screen:
Enter some data into the form and click on View Gallery to see the uploaded image as below: