Use react router to save also a page state

It's my first time I use react-router and I have some doubts. My web page is composed by a homepage and other pages containing an accordion. Each of these pages have the same structure, what change is the item of the accordion based on some data.

Here the working code.

As you can see, Homepage contains 3 buttons, if you click on one of them, the web app goes to /[title], that page contains a menu and the accordion. The default open accordion item is the first one.

Ok, that works. My problem now is that if you click on a button of the menu in the /[title] page, you go to another page but the open accordion item is the same as the previous.

Example:

  • Homepage: click on tomato
  • App goes to /tomato, the open accordion item is section 0
  • Click on section 2 -> section 0 will close and section 2 will open
  • Click on blue, app goes to /blue the open accordion item is section 2 and not section 0!

I think I can save in a global state the open accordion index and reset it to 0 when user clicks on a menu button but I'm asking if there is a way to save the index in the url like for example:

/[title]/[index] or /[title]#[index]

and use it like a state, so make it always updated.

I didn't know how to do that. I read the documentation but I can't find something similar.

Thanks a lot!


You could persist the active section for each page in state somewhere, but IMO there's a simpler way. Add the key prop from the route to the Page component so when the route path changes you can signal to React to remount the Page component, thereby resetting it to select the first accordion section.

{dataset.map((page) => (
  <Route
    key={page.title}
    path={page.title}
    element={<Page key={page.title} page={page} activeSub={0} />}
  />
))}

Edit use-react-router-to-save-also-a-page-state