In this post I will show how to use React Router 4 to add routing to a React application.
I am new to routing in React, but I really like the simplicity of the Router.
So far, the biggest difference from other routers I’ve used is that a route serves as both route definition and router outlet.
Meaning, the Route element not only defines meta data for the route, it also marks where the routed component is inserted in the DOM.
A route can be as simple as a single component, but you can also define more complex, nested routes.
Nested routes just means you have a multi level url where each fragment maps to a component in a component hierarchy.
Let’s create a demo application with some basic routing.
I start by defining the Router collection in my outermost component like so:
The greeting route is an example of a single level route. The /greeting url is mapped to a single Greeting component.
The /about route is slightly more complicated since it nests two components. The full url will be /about/descr, but I start by defining the "/about" root segment in the outer Route element.
Inside the mapped About component I define the second part of the route as a new Route element. Both segments work in tandem to define the final /about/descr route.
Here is the About component with its nested Description component:
The source is available on Github in case you want to try it out.