Using React Router 4

One Route, Multiple Places

One Route, Multiple Places

Because Route components are pretty much just components that show or hide another component depending on if the path prop matches the current URL, we can put multiple routes that match the same route in multiple places in our app, and React Router will handle showing them all. Let's explore this by adding a simple Add a User button to the sidebar when we are on a matching /user route.

We will also show how we can use the render prop on a Route component to render JSX instead of the component prop.

In the Cms component, add a Route underneath the other Link component we have and above the "Logout" button in the Sidebar already.

  render={() => (
    <Link to="/users/new">
      <Menu.Item name="new-user">
        <Icon name="plus" />
        Add a User

Here we have created another route that will match /users. Notice, it has a render prop instead of a component prop. This is handy for inlining components instead of creating a whole new component somewhere else. You should use the render prop when inlining JSX to show in a route instead of the component prop because the component prop will unmount and remount a component each time. This is wasted effort on React's part. In our code above, we are just returning a Link to our new user page.

Keep in mind that since this isn't in the Switch we created earlier, it will display in addition to any other routes that may display at the same time.

View this in the browser. Go to /users/1/edit. Notice how the "Add a User" button shows up in the sidebar. Now go to /thisdoesntexist and notice how it disappears. It's that simple.

In the next video, we will explore how we can protect certain routes by redirecting users away from protected pages if tey shouldn't have access to them.