react router dom v6

React Router Dom v6

If you are building a complex React application, it is important to have a good routing system in place. React Router is a popular library for handling routing in a React application. Version 6 of the library, React Router Dom v6, was recently released with some exciting new features and changes.

New Features

  • Routes as components: In previous versions of React Router, routes were defined using JSX syntax. However, in v6, routes are defined as components using the <Route> component.
  • Route matching: In v6, route matching has been simplified. Routes will match based on the order they are defined in the router configuration.
  • Improved TypeScript support: v6 has improved TypeScript support with better type definitions and more type safety.
  • Smaller package size: The size of the package has been reduced compared to the previous version.

Changes

  • No more static routes: In previous versions of React Router, routes were defined statically. However, in v6, routes are now defined dynamically using the <Routes> component.
  • No more withRouter: In v6, there is no need to use the withRouter higher-order component to access the router props. Instead, the router props are passed down through context.
  • No more switch: In previous versions of React Router, the <Switch> component was used to ensure that only one route was matched at a time. In v6, this is no longer necessary because routes are matched based on their order.
  • Route params: In v6, route parameters are now accessed using the useParams hook instead of being passed as props.

Code Example


import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

import Home from './Home';
import About from './About';
import NotFound from './NotFound';

const App = () => {
  return (
    <Router>
      <Routes>
        <Route path="/" element=<Home /> />
        <Route path="/about" element=<About /> />
        <Route path="*" element=<NotFound /> />
      </Routes>
    </Router>
  );
};

export default App;

In this example, we are using the <Routes> component to define our routes dynamically. We have three different routes: one for the home page, one for the about page, and one for any other path (which will display a 404 page). Note that we are using the element prop to define the component that should be rendered for each route.

Overall, React Router Dom v6 offers some exciting new features and changes that make it easier to handle routing in a complex React application.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe