This was from a sidebar navigation snippet. In this example, they are trying to describe what classes should be present to communicate to the user which item in the menu reflects the current page.
If I was using React Router, there is a built in way to handle this. But using Next.js, the
next/linkhas no concept that the page you are on is the current one. Instead you have to handle this yourself.
By creating your own Link component, you can wrap the Next.js Link component to make it a little smarter. Not only do we want to tell the component what classes should apply for the current page, but also what should apply when we are not the current page. Additionally, we may need to do this for children as well.
In the example below, the
atag needs to be adjusted based on if it is the active link. And the sag needs to be adjusted so the icon has the correct coloring as well, otherwise it would break the theme.
We can achieve this by creating a
ActiveLink.jsxcomponent that takes the default and current class string. We will also append a Child component to the ActiveLink so that we can share the state of active with the child.
We can now rewrite this html and apply the correct information using our custom ActiveLink component. Now when we are on the current page, the
ActiveLinkcomponent can identify this because we checked our current page against the
next/router. We then know if we need to add any classes.
The last piece is that we use
ActiveLink.Childto give this same behavior to a child farther down the tree. This time it does not have to check against the
next/router, and instead uses the parentActive` Boolean to determine how it should behave.