The Create React App tool does not contain page routing.
React Router is the most popular solution.
Add React Router
To add React Router to your application, perform the following in the terminal from the application’s root directory:
npm i -D react-router-dom
NOTE:This tutorial utilizes React Router v6.
If you are updating from version 5, you will need to use the @latest flag.
npm i -D react-router-dom@latest
Folder Structure
To develop an application with several page routes, we’ll start with the file structure.
Within the srcfolder, we’ll build a folder called pagescontaining numerous files.
src\pages\:
Layout.js
Home.js
Blogs.js
Contact.js
NoPage.js
Each file will have a very basic React component.
Basic Usage
We will now use our Router in the index.js file.
Example
Use React Router to route pages depending on URLs:
index.js:
import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Layout from "./pages/Layout";
import Home from "./pages/Home";
import Blogs from "./pages/Blogs";
import Contact from "./pages/Contact";
import NoPage from "./pages/NoPage";
export default function App() {
return (
}>
} />
} />
} />
} />
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render();
Example Explained
We wrap our content first with <BrowserRouter>.
Then, we specify our <Routes>. An application may have several <Routes>. Our basic example only needs one.
Routes can be nested. The first <Route>, with a route of /, renders the Layout component.
The nested <Route>s inherit and extend the parent route. So the blogspath is concatenated with the parent, resulting in /blogs.
The Homecomponent route does not contain a path, but rather an indexattribute. That makes this route the default path for the parent route, which is /.
Setting the path to * serves as a catch-all for any unknown URLs. This is ideal for a 404 error page.
Pages / Components
The Layoutcomponent has <Outlet> and <Link> components.
The <Outlet>displays the current route selected.
<Link> sets the URL and tracks surfing history.
When linking to an internal path, we shall use <Link> instead of <a href=””>.
The “layout route” is a shared component that adds common material to all pages, such as a navigation menu.
Layout.js:
import { Outlet, Link } from "react-router-dom";
const Layout = () => {
return (
<>