How to use react-router-dom v6
React Router is a popular library for routing in a React application. It provides several components that can be used to define the routes in your application and navigate between them. Here is an example of how you can use React Router in a React application:
- Install the library by running
npm install react-router-dom
oryarn add react-router-dom
in your project’s root folder. - Import the
BrowserRouter
component fromreact-router-dom
at the root of your application. This component will be used to wrap the entire application and manage the routing.
import { BrowserRouter } from 'react-router-dom'; function App() { return ( <BrowserRouter> {/* Your routes and components go here */} </BrowserRouter> ); }
- Define your routes using the
Route
component. TheRoute
the component takes two props: path and component. The path prop specifies the URL path that the route should match and thecomponent
prop specifies the React component that should be rendered when the route is active.
import { Route } from 'react-router-dom'; function App() { return ( <BrowserRouter> <Route path="/home" component={Home} /> <Route path="/about" component={About} /> <Route path="/contact" component={Contact} /> </BrowserRouter> ); }
- Use the
Link
component to create links between your routes. TheLink
component takes ato
prop that specifies the destination route, and it renders a clickable element that will navigate to the specified route when clicked.
import { Link } from 'react-router-dom'; function Navbar() { return ( <nav> <Link to="/home">Home</Link> <Link to="/about">About</Link> <Link to="/contact">Contact</Link> </nav> ); }
- You can also use the
useParams
hook fromreact-router-dom
to access the dynamic segments of a route’s path in the component that is rendered by the route. For example, if you have a route with a path of/products/:productId
, you can use theuseParams
hook to get the value ofproductId
in theProduct
the component that is rendered by the route.
import { useParams } from 'react-router-dom'; function Product() { const { productId } = useParams(); return <div>Product: {productId}</div>; }
I hope this helps! Let me know if you have any questions regarding React Router in a React application: