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:

  1. Install the library by running npm install react-router-dom or yarn add react-router-dom in your project’s root folder.
  2. Import the BrowserRouter component from react-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>
  );
}
  1. Define your routes using the Route component. The Route the component takes two props: path and component. The path prop specifies the URL path that the route should match and the component 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>
  );
}
  1. Use the Link component to create links between your routes. The Link component takes a to 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>
  );
}
  1. You can also use the useParams hook from react-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 the useParams hook to get the value of productId in the Product 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:

About Post Author