Setting Up React Router
Key Concepts
- Installing React Router
- Configuring Routes
- Using Route Components
- Navigating Between Routes
- Passing Route Parameters
Installing React Router
To use React Router in your project, you need to install it via npm or yarn. Open your terminal and run the following command:
npm install react-router-dom
This command installs the necessary packages to enable routing in your React application.
Configuring Routes
Once React Router is installed, you need to configure your routes. Import the necessary components from 'react-router-dom' and define your routes using the Route component.
Example:
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
function App() {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</Router>
);
}
Using Route Components
The Route component is used to define which component should be rendered based on the current URL. The exact prop ensures that the route matches exactly, preventing nested routes from being rendered.
Example:
<Route exact path="/" component={Home} />
In this example, the Home component will be rendered when the URL is exactly '/'.
Navigating Between Routes
To navigate between different routes, you can use the Link component from 'react-router-dom'. The Link component creates an anchor tag that navigates to the specified route without refreshing the page.
Example:
import { Link } from 'react-router-dom';
function Navigation() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
);
}
Passing Route Parameters
You can pass parameters in the URL using the Route component. These parameters can be accessed in the component using the match prop.
Example:
<Route path="/user/:id" component={User} />
function User({ match }) {
return <div>User ID: {match.params.id}</div>;
}
In this example, the User component receives the id parameter from the URL and displays it.
Analogies
Think of React Router as a GPS system for your web application. The routes are like different destinations, and the Route component helps you navigate to the correct destination based on the URL. The Link component is like a clickable map that allows you to move between destinations without leaving the app.
Another analogy is a library catalog. The routes are like different sections of the library, and the Route component helps you find the right section based on the book's category. The Link component is like a catalog index that allows you to quickly jump to different sections.