React Router: Redirect to a different component

Viewed 51

There are two main links on the landing page and then when user clicks on the option it should redirect to that component and not render the component below in the same page.

But, rather than going to the next page, the component is displayed below like a navbar.

const MainRoutes = () => {
  return (
    <ReactRouterDOM.HashRouter>
      <div className='routes'>
        <nav>
          <ul>
            <li>
              <Link to='/team-member'>Team Member</Link>
            </li>
            <li>
              <Link to='/moderator'>Moderator</Link>
            </li>
          </ul>
        </nav>
        <Route path='/team-member' component={TeamMember} />
        <Route path='/moderator' component={Moderator} />
      </div>
    </ReactRouterDOM.HashRouter>
  );
};

const App = () => {
  return (
    <div className='app'>
      <MainRoutes />
    </div>
  );
};
1 Answers

You need to wrap your routes in Switch:

<Switch>
  <Route exact path='/team-member' component={TeamMember} />
  <Route exact path='/moderator' component={Moderator} />
</Switch>

As Switch renders the first child <Route> that matches the location. Also, it renders a route exclusively (which you need).

Edit:

If you don't want to show NavBar at other components but only at index route /, you can do this:

const MainRoutes = () => {
  return (
    <HashRouter>
      <div className="routes">
        <Switch>
          <Route exact path="/" component={NavBar} />
          <Route exact path="/team-member" component={TeamMember} />
          <Route exact path="/moderator" component={Moderator} />
        </Switch>
      </div>
    </HashRouter>
  )
}

NavBar:

function NavBar() {
  return (
    <nav>
      <ul>
        <li>
          <Link to="/team-member">Team Member</Link>
        </li>
        <li>
          <Link to="/moderator">Moderator</Link>
        </li>
      </ul>
    </nav>
  )
}
Related