2

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

Shadow Walker
  • 979
  • 5
  • 27
  • 51
  • 1
    By default, the URL *shouldn't* change when you refresh a page, so some setting of yours is preventing this, redirecting you to `/` when you refresh. The code you show does not redirect in any way; it simply sets a boolean attribute on a menu link. –  Jul 29 '20 at 05:27
  • 1
    Oh my, I didn't even see that quotes mess until now. You can use `to={"/" + localStorage.getItem("selectedItem")}` –  Jul 29 '20 at 05:33

1 Answers1

2

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>)
}
Drag13
  • 5,859
  • 1
  • 18
  • 42