0

I have a sidebar with buttons links that targets div id and URL ends with #id_name. Now I want to render data that matches #id_name in a map loop using this code:

<div>
  {entries.map((item, index) => {
    if (asPath.endsWith(`#${item.section}`))
      return (
        <div id={item.section} key={index}>
          <h3>{item.title}</h3>
          <p>{item.summary}</p>
        </div>
      );
  })}
</div>

It works on refresh if #id_name matches item.section but if I click another link nothing happens even if item.section matches #id_name.

How can I re-render the map loop without refreshing or leaving the page when #id_name changes?

Mintee
  • 505
  • 4
  • 22
  • where do you change URL when click happens? – abolfazl shamsollahi Oct 23 '22 at 14:50
  • @abolfazlshamsollahi The button links href's #id_name and address bar changes. – Mintee Oct 23 '22 at 14:54
  • If you want to detect changes in the URL hash, see [How to detect change in the URL hash in Next.js?](https://stackoverflow.com/questions/69343932/how-to-detect-change-in-the-url-hash-in-next-js). You can then update a state variable to trigger a re-render. – juliomalves Oct 23 '22 at 22:44
  • 1
    @juliomalves I did figure it out, see my own answer. But thanks, that also helpful. – Mintee Oct 24 '22 at 09:57

2 Answers2

0

If you want to re-render to work
asPath or entries should be in useState or redux state.
I think asPath is more correct one for this case... try using useEffect and useState

biglol
  • 36
  • 3
0

I did figure it out without using a state. Instead of using Next Link or <a> on button links, I used push from useRouter. Weird how that one works.

  const router = useRouter();

  const handleHref = (link) => {
    router.push(link);
  };

  <Botton onClick={() => handleHref(`#${String(item.section).replace(/ /g, "-")}`)}>{item.section}</Botton>
Mintee
  • 505
  • 4
  • 22