Last week I wrote about setting up a project with Create React App and then decided to add some additional pages there with React Router.
Here is a result of the following steps deployed through Netlify. The repo can be seen here.
React Router is a library for React that helps you arranging all the pages of the project (routes). It can be installed in the root folder of the project with the following command in the terminal (current version is 6, otherwise it can be checked in the docs; can be installed with npm or Yarn):
npm install react-router-dom@6
Then you need to import it in the file where you want to set up the routing structure. I usually do this in the App.js:
import { BrowserRouter, Routes, Route } from “react-router-dom”
Or you can shorten the first import like this (which oftentimes can be seen in the tutorials):
import { BrowserRouter as Router, Routes, Route } from “react-router-dom”
I prefer leaving it as BrowserRouter.
You then wrap everything within the App function with <BrowserRouter></BrowserRouter>, and all the routes will be wrapped with <Routes></Routes>.
After this each of the routes is created with the <Route /> tag inside of which you put path to the page and element (page/component) that the page will display. E.g.:
<Route path=”/” element={<Home />} />
And then you add more routes with paths and elements. Here you have two pages — Home and Article, first one with the root path, second one with the root/article path:
After this you can create a navbar to navigate between your pages with a <Link></Link> tag (which is basically a <a></a> tag that can be styled any way you want). I created a separate component NavBar and placed it outside of the Routes so it can be displayed on every page:
And the NavBar component looks like this (make sure to import Link there):
One last thing to add to set up the basic routing structure is the error-page when route doesn’t match any of the existing ones (e.g. /asdf). This can be done by adding another route with a path=”*” and for the element you put the page/component where you add you error-page content. For example:
Here we have a Home page, an Article page and everything else will be redirected to the Error page.
There’s obviously a ton of other things that can be done with React Router (check the docs) but this is how it’s basic structure looks like.
As usual, if you read till this point and find it a smidge useful, I thank thee, kind person.