Using React Router 4

Our First Route

Our First Route

Now that the router is setup, let's add our first route so that the users tables only shows at the /users route. In src/fe/components/Cms/index.js, replace <Users /> with the following.

<Route path="/users" component={Users} />

Also make sure to import the Route component at the top of the file.

import { Route } from 'react-router-dom';

Let's break this down. First we are declaring we want a route added here. We then say we want this route to be displayed when the path in the URL is /users. When this matches, we want to render the Users component. Pretty simple!

View this in the browser by going to localhost:3000/users. You should see the same screen as before. However, try going to localhost:3000/somethingelse. You will see just the sidebar. Nothing will be in the content area of the application. This is because the path in the URL doesn't match /users. Therefore, it just won't show our component.

This works great, but getting back to our users route is kinda annoying since we have to manually type it in the URL. It'd be great if we could just link to it. Well we can! Let's do that now. Add the Link component to our import.

import { Route, Link } from 'react-router-dom';

Then wrap the "Users" Menu.Item in the Link component, telling it to link to our /users route.

<Link to="/users">
  <Menu.Item name="users">
    <Icon name="users" />

Now go to localhost:3000/somethingelse. Click on our "Users" navigation item. It took us to our /users route! That's stupid simple.

Now that we know how to setup routes and link to them, let's talk about how to manage route params in the next one.