Web Hosting Forum - Net Hosting Talk

We are a community of individuals and businesses passionate about web hosting. Let's build, learn, and grow together.

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

JohnnieNiz

Novice
Member
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>
  )
}
 
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
  • Advertisement

    Back
    Top