Skip to content
Advertisement

ReactJS :: How to Show Only Relevant Menu Items and Hide Other Menu Items Upon Page Change

I am doing an online Full Stack Web Developer Bootcamp and have just been introduced to React JS events and am having some difficulty implementing the following instructions:

The menu component should only display relevant items. For example, if the user is on the “shop” page, the “shop” menu item should no longer be displayed.

I have tried executing this via the “activeClassName” and CSS method, but this is unfortunately not recognized as a DOM property.

I have also tried following guides and previous Stack Overflow questions’ answers that offer solutions such as this: https://www.pluralsight.com/guides/how-to-show-and-hide-reactjs-components

Unfortunately I have had no success as yet and would appreciate any assistance that anyone is willing to offer. It would be great to learn how to make use of this for future projects.

My code is as follows:

Navigation.js

JavaScript

App.js

JavaScript

Please do let me know if any further information is required.

Advertisement

Answer

Simple.

At your Navigation component, import useLocation.

JavaScript

Add location variable and isCurrentURL function.

isCurrentURL function will determine if the menu’s URL is the current URL.

JavaScript

Now wrap all your NavItem like this:

JavaScript

Alternatively, you can store your menus in an array, then iterate and check.

That’s it. So, the current URL link will not be rendered.

Advertisement