Introduction to React Router
React Router is a popular library for managing client-side routing in React applications. It allows you to define routes for your application and navigate between them.
Installing React Router
To install React Router, run the following command in your terminal:
npm install react-router-domBasic Routing
To use React Router, you need to wrap your application with the `BrowserRouter` component.
import React from 'react';
import { BrowserRouter } from 'react-router-dom';function App() {
return (
<BrowserRouter>
<!-- Your application code here -->
</BrowserRouter>
);
}Defining Routes
To define routes, you use the `Route` component.
import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';function App() {
return (
<BrowserRouter>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
</BrowserRouter>
);
}function Home() {
return <h1>Home</h1>;
}function About() {
return <h1>About</h1>;
}In this example, we define two routes: `/` and `/about`. The `Home` component is rendered when the URL is `/`, and the `About` component is rendered when the URL is `/about`.
Link Component
To navigate between routes, you use the `Link` component.
import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';function App() {
return (
<BrowserRouter>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
</BrowserRouter>
);
}In this example, we define two links: one to the `/` route and one to the `/about` route.
Nested Routes
To define nested routes, you can use the `Route` component inside another `Route` component.
import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';function App() {
return (
<BrowserRouter>
<Route path="/users" component={Users} />
</BrowserRouter>
);
}function Users() {
return (
<div>
<h1>Users</h1>
<Route path="/users/:id" component={UserProfile} />
</div>
);
}function UserProfile() {
return <h1>User Profile</h1>;
}In this example, we define a route `/users` that renders the `Users` component, and a nested route `/users/:id` that renders the `UserProfile` component.
Example Code
Here's an example of a simple React app that uses React Router:
import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';function App() {
return (
<BrowserRouter>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
</BrowserRouter>
);
}function Home() {
return <h1>Home</h1>;
}function About() {
return <h1>About</h1>;
}
Here's a practice exercise:
Create a simple React app that uses React Router to navigate between three routes: `/`, `/about`, and `/contact`.
Hint: Use the `BrowserRouter`, `Route`, and `Link` components to define the routes and navigate between them.