How can I show/hide some parts of the component based on the URL path?

Whether you're a budding designer looking for some tips or a HTML guru looking to advise, the Website Design & Graphics forums are the perfect place for you. Want your site reviewed? Post it here for our members and moderators to critique.
Post Reply
JohnnieNiz
Newbie
Posts: 1
Joined: Mon Jan 20, 2020 10:08 am

#1

Hello,

I want to change the navbar items based on the URL without having two different navbar components. My navbar has four links on the left side and four links on the right, but I want to display each side once a time.

E.g., when I'm on pages 1 to 4, I want to show only the left side menu, and when I'm on page-4 to 8, show the right side menu. How can I achieve that?

Layout.js

Code: Select all

...
export default class Layout extends Component {
  render() {
    return (
      <div>
        <Route path="/:name" component={Navbar} />
        <SomeContentComponent />
      </div>
    );
  }
}
Navbar.js

Code: Select all

const Navbar = ({ match }) => {

  const page = match.params.name

  return (
    <div>
      <ul className="left">
        <li><Link to="/page-one">Page 1</Link></li>
        <li><Link to="/page-two">Page 2</Link></li>
        <li><Link to="/page-three">Page 3</Link></li>
        <li><Link to="/page-four">Page 4</Link></li>
      </ul>
      <ul className="right">
        <li><Link to="/page-five">Page 5</Link></li>
        <li><Link to="/page-six">Page 6</Link></li>
        <li><Link to="/page-seven">Page 7</Link></li>
        <li><Link to="/page-eight">Page 8</Link></li>
      </ul>
    </div>
  )
}


User avatar
edwin
Junior Member
Posts: 31
Joined: Thu Sep 28, 2017 6:17 pm

#2

You can conditionally render left or right div like this:

Code: Select all

const Navbar = ({ match }) => {

  const { url } = match;
  const showLeft = ['/page-one', '/page-two', '/page-three'].indexOf(url) > -1;

  return (
    <div>
      {showLeft && (<ul className="left">
         <li><Link to="/page-one">Page 1</Link></li>
        <li><Link to="/page-two">Page 2</Link></li>
        <li><Link to="/page-three">Page 3</Link></li>
        <li><Link to="/page-four">Page 4</Link></li>
      </ul>
      )}
      (!showLeft && (
      <ul className="right">
       <li><Link to="/page-five">Page 5</Link></li>
        <li><Link to="/page-six">Page 6</Link></li>
        <li><Link to="/page-seven">Page 7</Link></li>
        <li><Link to="/page-eight">Page 8</Link></li>
      </ul>
      )}
    </div>
  )
}
Post Reply
  • Information
  • Who is online

    Users browsing this forum: No registered users and 1 guest