Because React is only concerned with the state of its components, If set up correctly, it only re-renders the components that need to be updated. This makes it possible for dynamic rendering to happen.
If you want to switch pages in a react application there are ways to do it dynamically, such as conditional rendering of a “Page”. Conditional rendering is useful for small, non-complex applications. For more robust applications that may have a more intricate tree structure, there is a more powerful tool.
React Router is a library for handling routing in React. It is more powerful than conditional rendering by allowing the developer to use, redirection, parameters, dynamic URL’s, and Props.
For the sake of this tutorial, we will only go over setting up the basics for a React application to use React Router.
To begin, You need to create a new React application of course. If You don’t know how to do this, check out my tutorial on setting up a react application here.
Once you have your application all set up, We are going to set up the application to make it as basic as possible.
Next, we are going to make 5 simple files, App.js, index.js, Page1.js, Page2.js, and Page3.js.
After this is finished, we will set up the index.js to render the App.js function.
Now that this step is complete, we will install the react-router-dom dependency so we can set up React Router. We just need to open the terminal in the directory where our react project is and use the command 'npm install react-router-dom'.
Once we’ve done this, we can start setting up react-router.
In the App component, we need to import some components from react-router.
These components are Browser Router, Switch, and Route
We also need import the Page components, and wrap them in routes.
With this done, we can now set up our Router.
The router will allow any components inside of it to be routed.
Inside the routes we need to set the route paths that determine which component will be rendered.
With this done, We can now start the application and go to any of the routes that we set up, and the components will be rendered.
the 3 routes are
We are essentially finished but we can take it a couple of steps further to really drive it home.
We can add links to each of the pages so that we can switch pages whenever we need to. All we need for this, is to import Link from react router.
Finally, If we wanted to have a navigation bar at the top of the page for every page, we don't need to add it to every page component, we only need to add it at the top of the router in the app component.
This is all we need to get started with using react router. Now you should be able to setup simple routes, and links. You can build on this knowledge to create redirections, histories, directories, navbars, and much more.