React Router is a popular library for adding routing to React applications. It provides a simple way to declaratively specify which components should be rendered based on the current URL. In this blog, we’ll look at how to use React Router to add routing to a React app.
To start, you’ll need to install the react-router-dom
library, which provides the components and functions you’ll need to add routing to your React app. You can install it using npm or yarn
npm install react-router-dom
or
yarn add react-router-dom
Once you’ve installed the library, you’ll need to import the BrowserRouter
component from react-router-dom
and wrap your entire app with it. The BrowserRouter
component uses the HTML5 history
API to keep the UI in sync with the current URL.
Here’s an example of how to use the BrowserRouter
component to wrap your app:
import { BrowserRouter } from 'react-router-dom'; ReactDOM.render( <BrowserRouter> <App /> </BrowserRouter>, document.getElementById('root') );
Next, you’ll need to define your routes. A route is a declarative way to specify which component should be rendered for a given URL. In React Router, you can use the Route
component to define a route. The Route
component takes a path
prop, which specifies the URL pattern for the route, and a component
prop, which specifies the component that should be rendered when the route matches the current URL.
Here’s an example of how to define some routes using the Route
component:
import { Route } from 'react-router-dom'; function App() { return ( <div> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> <Route path="/users/:id" component={User} /> </div> ); }
In the example above, the Home
component will be rendered for the root URL (/
), the About
component will be rendered for the /about
URL, and the User
component will be rendered for URLs that match the pattern /users/:id
. The :id
part of the URL is a dynamic segment, which means that it can match any value. For example, the route /users/1
would match the User
component, and the route /users/2
would also match the User
component.
To navigate between routes, you can use the Link
component from react-router-dom
. The Link
component takes a to
prop, which specifies the URL that the link should navigate to when clicked.
Here’s an example of how to use the Link
component to navigate between routes:
import { Link } from 'react-router-dom'; function Home() { return ( <div> <Link to="/about">About</Link> </div> ); }
In the example above, clicking the “About” link will navigate the user to the /about
URL.
Thanks for reading the blog ask your doubts in comment section