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

import React from 'react';
// Imported components from React Bootstrap.
import {Container, Col, Row, Navbar, Nav, NavLink, NavItem} from "react-bootstrap";

function Navigation() {
  return (
    <div>
      <Navbar id="navbar">

        <Container>
          <Row id="navrow">

            <Col id="navcol" className="d-none d-lg-flex">
              <Nav className="mrx-auto" navbar>

                <NavItem className="navitem">
                  <NavLink className="navlink" href="/Profile"><img src="./images/profile.png" alt="View Your Profile" title="View Your Profile" id="profileimg" /></NavLink>
                </NavItem>

                <NavItem className="navitem">
                  <NavLink className="navlink" href="/">HOME</NavLink>
                </NavItem>

                <NavItem className="navitem">
                  <NavLink className="navlink" href="/Shop">SHOP</NavLink>
                </NavItem>

              </Nav>
            </Col>

          </Row>
        </Container>

      </Navbar>
    </div>
  )
}

export default Navigation;

App.js

// Imported react libraries and components.
import React, { Component } from 'react';
// Imported css styles.
import './App.css';
// Imported components.
import Navigation from './components/Navigation';
import Header from './components/Header';
import Profile from './components/Profile';
import Landing from './components/Landing';
import Products from './components/Products';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
// Constructed a boolean value to determine whether a user is signed in or not. 
const loggedIn = true;
// Constructed a map array of objects to display the "Landing/ About Us" information. 
const landings =
  [{
    id: "1",
    landing_description: "We officially opened our doors June of 2020 and have created an environment that caters for anyone, no matter your fitness level. We pride ourselves in delivering professional services and providing top-performing equipment and facilities to our clients. Our mission is to create a healthier lifestyle for our staff, as well as for our customers. Our job is to provide you with a better quality life, whether it is upping your fitness levels or whether you want that body that you have been longing for."
  }];
// Constructed a map array of objects to display the products' information. 
const products =
  [{
    id: "2",
    product_name: "Classic Package",
    product_price: "R250.00 P/M",
    product_image: "./images/gym.jpg",
    product_description: "We have all of the equipment that is needed to enable anyone to achieve their ultimate goal. Our gym also have an indoor pool and a canteen for healthy refreshments and food items. Gain access to our facilities and start your transformation."
  },
  {
    id: "3",
    product_name: "Elite Package",
    product_price: "R350.00 P/M",
    product_image: "./images/spinning.jpg",
    product_description: "This membership plan gains you access to all of the equipment, as well as give you the option of joining up to two of our classes. Whether you are into spinning classes, yoga, aerobics, boxing or showing off your moves in a Zumba Fitness class."
  },
  {
    id: "4",
    product_name: "Pro Package",
    product_price: "R450.00 P/M",
    product_image: "./images/personal.jpg",
    product_description: "This membership plan grants you full access to all of our facilities and classes. In addition you also get assiged a personal trainer that will help you with your work-out plans, as well as meal plans. This is the ultimate package, which should give you your desired outcome at a faster pace."
  }];

console.log(typeof products);
// Rendering and returning data to be exported to Index.js.
class App extends Component {
  render() {
    return (
      <div>
        <BrowserRouter>
          <div className="App">
            {/* Included a link to the App.js stylesheet. */}
            <link
              rel="stylesheet"
              href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
              integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS"
              crossOrigin="anonymous"
            />
            <Navigation />
            {/* Added Header component. */}
            <Header name="Code Reviewer" loggedIn={loggedIn} />
            {/* Added Landing component. */}
            <Switch>
            <Route exact={true} path="/" render={() => (
              <Landing landings={landings} />
            )} />
            <Route path="/Profile" render={() => (
            <Profile />
            )} />
            {/* Added Products component. */}
            <Route path="/Shop" render={() => (
              <Products products={products} />
            )} />
            </Switch>
          </div>
        </BrowserRouter>
      </div>
    );
  }
}

// Exporting to render App component in Index.js where the ReactDom.Render() method is called.
export default App;

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

Advertisement

Answer

Simple.

At your Navigation component, import useLocation.

import { useLocation } from 'react-router-dom';

Add location variable and isCurrentURL function.

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

const location = useLocation();

const isCurrentURL = (url) => {
    return location.pathname.toLowerCase() === url.toLowerCase();
}

Now wrap all your NavItem like this:

{ !isCurrentURL('/Profile') ? <NavItem className="navitem">
                    <NavLink className="navlink" href="/Profile"><img src="./images/profile.png" alt="View Your Profile" title="View Your Profile" id="profileimg" /></NavLink>
                  </NavItem> : null }

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