All codes below in codesandbox — https://codesandbox.io/s/exciting-cloud-e2ts7?file=/src/App.js:248-475
If you are a fresh beginner in React.js this topic might be a little bit complex for you, but I will do my best to help you build a foundation for your future projects. So unlike server-side rendering, react uses client-side rendering which means all navigations happen independently on the client-side. In this article, we will see how we can set up page navigation in other words routing in react.
To apply routing in react we use a popular npm package called react-router-dom, so let’s install it, in your terminal write this:
npm install react-router-dom
Now we have it we can start setting up our routing. In order to use react-router-dom features, we should wrap our app using
BrowserRouter which we import from react-router-dom
Now we can specify our routes using
Route component from react-router-dom. It takes two main props
path property to specify the path and
component property which is going to be rendered in that path.
Notice that I am importing
Home component which I have pre-made. Now if we run our app using
npm start we can instantly see our
Home component be rendered because by default we are on
Let’s add some more pages: About —
/about , Contact us —
Cool, but when you go to
/contact path you will see something like this:
As you can see our
Home component is also getting rendered before
Contact component. And this is expected behavior, as official documentation said
This is by design, allowing us to compose
<Route>s into our apps in many ways, like sidebars and breadcrumbs, bootstrap tabs, etc.
This basically means that
/contact is matching
/contact routes at the same time. It might come in handy if we were applying something like sidebar, header, footer, etc which should appear in multiple routes. But in our case we want
Home component to be rendered only if it is
/ route. What we can do is that we can pass
exact attribute which ensures that our component gets rendered only if the route exactly matches. Like this:
Also, we have
Switch component which is used to ensure that only the first component whose path matches the route gets rendered, it might be helpful when you are working with dynamic URLs.
Congrats now you have a fully functional routing in your react app. This article might not be complete instruction but I hope it serves you as a foundation.
In the next part, I will show you how to work with dynamic routes, URL queries, react-router-dom related hooks, and much more.
All codes above in codesandbox — https://codesandbox.io/s/exciting-cloud-e2ts7?file=/src/App.js:248-475