Categories

Tuesday, July 16, 2024
#919814419350 therichposts@gmail.com
Reactjs

Reactjs Share Data Between Components Method 2 : LocalStorage + useState Hook

Reactjs Share Data Between Components Method 2 : LocalStorage + useState Hook

Hello my friends, welcome back to my blog. Today in this blog post, I am going to show you, Reactjs Share Data Between Components Method 2 : LocalStorage + useState Hook.

Live Demo

For reactjs new comers, please check the below link:

Guys here is the working code snippet and please follow carefully:

1. Guys you need to add this code into your first component like I added inside my Home.js file:

import {useState} from 'react';
function Home() {
    const [message, setMessage] = useState('');

    const handleChange = event => {
        setMessage(event.target.value);
        localStorage.setItem('message', event.target.value);
    };
    
    return (
       <div className="home container p-5">
            <p>Home</p>
            <input
                type="text"
                id="message"
                name="message"
                onChange={handleChange}
                value={message}
            />

            <h2>Message: {message}</h2>
        </div>
    );
}
export default Home;

2. Guys you need to add this code into your first component like I added inside my About.js file:

function About() {
    return (
       <div className="about container p-5">
        Getting shared data from Home.js file input message field : <strong>{localStorage.getItem('message')}</strong>
        </div>
    );
}
export default About;

I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad.

Jassa

Thanks

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 14, Angular 15, Angular 16, Angular 17, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.