Welcome to Web Hosting Forum - Net Hosting Talk

Register now and be part of our community! When you register with the Net Hosting Talk you can join in with topics, start new topics, and generally be a part of the first level of our community. It's also quick and totally free, so what are you waiting for?

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

JohnnieNiz

Newbie
Messages
2
Reaction score
0
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:
...
export default class Layout extends Component {
  render() {
    return (
      <div>
        <Route path="/:name" component={Navbar} />
        <SomeContentComponent />
      </div>
    );
  }
}

Navbar.js
Code:
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>
  )
}
 

edwin

Moderator
Messages
40
Reaction score
3
You can conditionally render left or right div like this:
Code:
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>
  )
}
 

Advertisement

Top