Loading lesson path
Concept visual
â® Previous Next â¯
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:
Without a router, your React application would be limited to a single page with no way to navigate between different views.
In the command line, navigate to your project directory and run the following command to install the package:
Formula
npm install react - router - domfunction App() {
return (<BrowserRouter>
{/* Your app content */}</BrowserRouter>
);
}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>;
}React Router uses three main components for basic routing:
: Creates navigation links that update the URL
: A container for all your route definitions
: Defines a mapping between a URL path and a component Let's add navigation links and routes for each link:
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>
);
}BrowserRouter wraps your app and enables routing functionality