Skip to content

Save a prop when moving away and coming back to page ReactJS

I have a username property that I have passed on from “log in” route to “product list” route using

return <Redirect to={{
    pathname: "/products",
    state: username

I then have a <Link to={'/products/${}'}>More info</Link> that sends me from “product list” to an “individual product”.

When I then come back to the “product list” <Link to={'/products'}>Back</Link>, the username is gone. Is there a way to keep the username, so when the user is logged in and moves back and forth between routes, it keeps being stored?

Here is the full code for my “product list” route where I want the username to be stored:

import React, {useState, useEffect} from 'react';
import './Products.css';
import {Link} from 'react-router-dom';

function Products(props) {

  const [products, setProducts] = useState([]);

  useEffect(() => {
    const fetchProducts = async () => {

      const data = await fetch("");
      const products = await data.json();
  }, []);

  let username = props.location.state;

  return (   
      <p className = "HelloUser">Hello, {username}</p>
      <p className = "ProductTitle">Our Selection</p>
      <div className = "ProductGrid">
        { =>(
        <div className = "ProductBox" key={}>
          <img className ="ProductImage" src={product.image} alt="did not load"/>
          <p className ="ProductName">{}</p>
          <p className ="ProductDiscountedPrice">{"£" + (Math.round(product.discountedPrice * 100) / 100).toFixed(2)}</p>
          <p className ="ProductPrice">{"£" + (Math.round(product.price * 100) / 100).toFixed(2)}</p>
          <Link to={`/products/${}`} className="MoreInfoButton">More info</Link>

export default Products;


SOLVED: Solved it by passing on the username prop further to the “individual product” component. That way when I hit back to the “product list”, the username stays.

Or even better storing Username in the sessionStorage.