Open In App

How to save an image to localStorage and display it on the next page?

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

Why localStorage?



Syntax:

window.localStorage   // It returns a Storage Object

Methods of localStorage:

  1. setItem(key, value): Used to save data to localStorage.
  2. removeItem(key): Used to remove data from localStorage.
  3. getItem(key): It read data from localStorage.
  4. 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: 

  1. Basic knowledge of React.
  2. 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:

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




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




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




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




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




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:


Article Tags :