bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/React/React Core
React•React Core

React Router

Concept visual

React Router

visit parent, then branch83161014

❮ Previous Next ❯

What is React Router?

React Router is a library that provides routing capabilities for React applications. Routing means handling navigation between different views. React Router is the standard routing library for React applications. It enables you to:

Create multiple pages in your single-page application

Handle URL parameters and query strings

Manage browser history and navigation

Create nested routes and layouts

Implement protected routes for authentication

Without a router, your React application would be limited to a single page with no way to navigate between different views.

Install React Router

In the command line, navigate to your project directory and run the following command to install the package:

Formula

npm install react - router - dom

Wrap Your App with BrowserRouter

Your application must be wrapped with the

BrowserRouter component to enable routing:

function App() {
return (

<BrowserRouter>

{/* Your app content */}

</BrowserRouter>

);
}

Create Views

To demonstrate routing, we'll create three pages (or views) in our application: Home, About, and Contact: We will create all three views in the same file for simplicity, but you can of course split them into separate files.

Example function Home() {
return <h1>Home Page</h1>;
}
function About() {
return <h1>About Page</h1>;
}
function Contact() {
return <h1>Contact Page</h1>;
}

Basic Routing

React Router uses three main components for basic routing:

Link

: Creates navigation links that update the URL

Routes

: A container for all your route definitions

Route

: Defines a mapping between a URL path and a component Let's add navigation links and routes for each link:

Example

Note that we need to import

Formula

BrowserRouter, Routes, Route, Link from 'react - router - dom'.
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
function Home() {
return <h1>Home Page</h1>;
}
function About() {
return <h1>About Page</h1>;
}
function Contact() {
return <h1>Contact Page</h1>;
}
function App() {
return (

<BrowserRouter>

{/* Navigation */}

<nav>

<Link to="/">Home</Link> |{" "}
<Link to="/about">About</Link> |{" "}
<Link to="/contact">Contact</Link>

</nav>

{/* Routes */}

<Routes>

<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />

</Routes> </BrowserRouter>

);
}

In this example:

BrowserRouter wraps your app and enables routing functionality

Link components create navigation links

Routes and

Route define your routing configuration

Nested Routes

You can have a

Previous

React CSS-in-JS

Next

React Transitions