Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How to Save an Image to localStorage and Display it on the Next Page?
Next article icon

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:

  • ReactJS
  • Local Storage

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
How to Save an Image to localStorage and Display it on the Next Page?

P

prasannareddyisireddy
Improve
Article Tags :
  • Technical Scripter
  • JavaScript
  • Web Technologies
  • ReactJS
  • Technical Scripter 2020

Similar Reads

    How to store an array in localStorage ?
    To store an array in localStorage refers to saving an array of data in the web browser’s storage that persists across sessions. This is useful for keeping data, like user preferences or temporary information, accessible even after refreshing the page or reopening the browser.What is Javascript local
    3 min read
    How to change a button text on click using localStorage in Javascript ?
    In this article, we will learn how to change a button text using Javascript localStorage when we click on the button achieved by adding HTML onclick event listener. Approach: HTML DOM Window localStorage allows us to store key-value pairs in our browser using an object. The name of the key should be
    3 min read
    What are the implications to redirecting images behind the image tag ?
    This article intends to make the readers understand all possible implications while redirecting images in an HTML document. We will cover the implications as well as approaches to avoid such scenarios and discuss simple examples for a brief illustration as well. Before that, let us go through the
    5 min read
    How to Store Data in Local Storage using AngularJS ?
    Angular JS is a typescript-based web application framework. It is supported by the Angular team of Google and open-source developers. It is a component-based framework allowing the developers to reuse the components created. It is well-suited for large and complex applications because of its well-de
    5 min read
    How to specify an image as a server-side image-map in HTML ?
    In image mapping, an image is specified with certain set of coordinates inside the image which act as hyperlink areas to different destinations. It is different from an image link since in image linking, an image can be used to serve a single link or destination whereas in a mapped image, different
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences