Open In App

How to Save an Image to localStorage and Display it on the Next Page?

Last Updated : 01 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Saving an image to localStorage allows you to access it throughout the app. It can also be displayed on the next page by accessing directly from the local storage.

Prerequisites:

Approach

To save an image to local storage and display on next page we will use localStorage.setItem to store the image data on localStorage. We will store the image title, message, and image url. Then access the image data using localStorage.getItem and display it on the next page.

We can use the local storage as shown below

Syntax:

// To save data to localStorage:
localStorage.setItem(key, value)
localStorage.setItem("firstName", "Mark Zuker berg");

// To read data from localStorage:
localStorage.getItem(key)

// Returns the string "Mark Zuker berg"
localStorage.getItem("firstName");

// To remove data from localStorage:
localStorage.removeItem(key)
localStorage.removeItem("firstName");

Steps to Create React Application

Step 1: Create your application using the following command:

npx create-react-app crud-application

Step 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

Step 3: To allow routing of web pages. Install the following module:

npm i react-router-dom

Project Structure:

Project-structure---react-localstorage

The updated dependecies in the package.json incudes:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.2",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},

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.

JavaScript
// Filename: App.js

import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import PostForm from "./PostForm";
import AllPost from "./AllPost";

function App() {
	return (
		<div className="App">
			<BrowserRouter>
				<Routes>
					<Route path="/" element={<PostForm />} />
					<Route path="/gallery" element={<AllPost />} />
				</Routes>
			</BrowserRouter>
		</div>
	);
}

export default App;
JavaScript
// Filename: index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
JavaScript
// 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 {
	constructor(props) {
		super(props);
		this.titleRef = React.createRef();
		this.imageRef = React.createRef();
		this.messageRef = React.createRef();
	}

	handleSubmit = (e) => {
		e.preventDefault();
		const title = this.titleRef.current.value;
		const message = this.messageRef.current.value;
		const image = this.imageRef.current.value;
		localStorage.setItem("title", title);
		localStorage.setItem("message", message);
		localStorage.setItem("image", image);
		this.titleRef.current.value = "";
		this.messageRef.current.value = "";
		this.imageRef.current.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={this.titleRef}
					/>
					<br />
					<br />
					<input
						style={inputFields}
						required
						type="text"
						placeholder="Paste your image URL here"
						ref={this.imageRef}
					/>
					<br />
					<br />
					<textarea
						style={inputFields}
						required
						rows="5"
						cols="28"
						placeholder="Enter Comment"
						ref={this.messageRef}
					/>
					<br />
					<br />
					<button style={postBtnStyle}>Post</button>
				</form>
				<Link to="/gallery">
					<button style={galleryStyle}>View Gallery</button>
				</Link>
			</div>
		);
	}
}

export default PostForm;
JavaScript
// 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;
JavaScript
// 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={"Uploaded post"}
					style={{ width: "100%" }}
				/>
				<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:



Next Article

Similar Reads