React-router displays the first route which satisfies the path, even aprtially,
that’s why adding
exact parameter to the first route is needed.
The third route has a path parameter “id”.
Sometimes we not only want to render some component in fixed place based on
routing, but possibly we want to display different page layout based on routing.
We can then use
Route inside of another
if we navigate to
/ we will display ONLY
HomePage. If we navigate to
anything else, we will display appropriate component under a
path="/(.+)" checks if there is anything after
Loading just one route
It might happen that a few routes satisfy the path. We might use
component around our routes to make sure that only one route is loaded.
It’s also a good practice to have a route to “Not Found” page at the end. It’s without a path, because it should “catch” anything that wasn’t caught by previous routes.
Navigation using components
There are two components to be used:
Link, but can add styling
Sometimes it’s useful to rended other components as
Menu.Item (Semantic UI somponent) will appear as normal, however it will
become a link to “/activities”.
NavLink, “active” clas will be set automatically when clicked on a
Menu.Item (class name can be changed, for Semantic UI “active” is correct).
exact property is needed if we want to highlight only the correct
When we use router, components have access to additional props, which have various functionalities, i.e. it shows path parameters:
If we want to use some custom path parameters that our component is supposed to
receive in URL (like id), we need to create interface for contents of
Component then needs to be typed.
RouteComponentProps is generic:
IDetailParams should contain data that will be in
Navigation using code
One of the props we get is
history. It has various methods like
push(), etc. We can use those to navigate.
Adding router props to root component
If a component was not render by router, we can add routing additions
(additional props like
history), by using
withRoute higher order function:
In this case we’re also using
observer from MobX.
Router keeps same scrollbar position when routing to different pages. It can be undesired.