React Router is a powerful library for handling routing in React applications. It allows you to create single-page applications with navigation, without the need for page reloads. This chapter will guide you through the process of setting up React Router, from installation to creating routes and links.
1. Installation
First, you need to install the react-router-dom package. This package contains the components and hooks needed for web-based applications.
npm install react-router-dom
2. Basic Setup
Once you have installed react-router-dom, you need to configure it in your application. Start by wrapping your main application component with a BrowserRouter component. This component will handle the routing logic for your application.
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
ReactDOM.render(
,
document.getElementById('root')
);
3. Creating Routes
Next, you define the routes in your application. Routes are defined using the Route component, which maps a URL path to a specific component.
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
const App = () => {
return (
);
};
export default App;
Switch
: TheSwitch
component renders the first childRoute
that matches the current URL.Route
: TheRoute
component takes two main props:path
andcomponent
. Thepath
prop defines the URL path, and thecomponent
prop defines the component to render when the path matches.