Return to site

REACT: Routing 🛣️

· react,fullstack

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 🗃️:

Each file will contain a very basic React component.

 

3️⃣ Basic Usage

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

 

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