In my react app, i have stored the respective page names in the local storage depending on the clicked page name i.e for a route say http://localhost:3000/Products
i have stored the name Products in the localstorage whenever i click on the page Products.
I want whenever i have a page refresh, instead of being redirected to the home page /
, my page persists on the page i was by confirming with the value in my localstorage.
My way does not work.
<NavLink to="/localStorage.getItem("selectedItem")" style={{ textDecoration: "none" }}>
<MenuItemComponent
title="Products"
icon={IconProducts}
onClick={() => this.onItemClicked("Products")}
active={localStorage.getItem("selectedItem") === "Products"}
/>
</NavLink>
From the above code, i want the page to direct me to http://localhost:3000/Products
since the value of localStorage.getItem("selectedItem") is Products
You need to get value from LocalStorage but you are using plain string. Should be like this:
const AppNaVLink = () => {
const link = `/${localStorage.getItem("selectedItem") ?? ''}`
return (
<NavLink to={link} style={{ textDecoration: "none" }}>
<MenuItemComponent
title="Products"
icon={IconProducts}
onClick={() => this.onItemClicked("Products")}
active={localStorage.getItem("selectedItem") === "Products"}
/>
</NavLink>)
}