Return to site

REACT: Routing 🛣️

· react

Create React App doesn't ❌ include page routing.

React Router is the most popular 🙌 solution.

 

1️⃣ Add React Router

To add React Router to your application, run this in the terminal from the root directory of the application:

npm i -D react-router-dom

 

2️⃣ Folder Structure

To create an application with multiple page routes, let's first start 🚀 with the file structure.

Within the src folder, we'll create a folder named pages with several files 🗃️:

src\pages\:
Layout.js
Home.js
Blogs.js
Contact.js
NoPage.js

Each file will contain a very basic React component.

 

3️⃣ Basic Usage

Now we will use our Router in our index.js file.

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 (
  <BrowserRouter>
   <Routes>
    <Route path="/" element={<Layout />}>
     <Route index element={<Home />} />
     <Route path="blogs" element={<Blogs />} />
     <Route path="contact" element={<Contact />} />
     <Route path="*" element={<NoPage />} />
    </Route>
   </Routes>
  </BrowserRouter>
 );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

 

4️⃣ Example Explained

We wrap 🎁 our content first with .

Then we define our . An application can have multiple . Our basic example only uses one.

s can be nested 🪺. The first has a path of / and renders the Layout component.

The nested s inherit and add to the parent route.

So the 'blogs' path is combined with the parent and becomes /blogs.

The Home component route does not have a path but has an index attribute.

That specifies this route as the default route for the parent route, which is /.

Setting the path to * will be a catch-all 🪝 for any undefined URLs. This is great for a 404 error ‼️ page.

#react #programming #routing