How to Handle The New V6 React Route

How to Handle The New V6 React Route

Version change causing error about Switch being unavailable in react-rou

For this article you'll need to understand the basics of react components, React folder structure and routes - the articles assumes you know react at least the basics

You want when you click on a link in the browser it navigates to another react page, then this is the guide for you. please note am using the version 6 new format.

  • Run npm install react-router-dom to install the dependency if you're using npm , for those using yarn run yarn add react-router-dom in the terminal
  • add import { BrowserRouter } from "react-router-dom" to your index.js file in the src folder to make it available for use
  • Assume you have your own components already setup if not, create 2 components, Login and Register
  • In the App.jsx or App.js file import/addimport { Routes, Route } from "react-router-dom" and also import the components import Login from "./Components/Login" and import Register from "./Components/Register"

  • Initially in v5 routes were rendered as <Route exact path="/register" component={Register} /> but this format currently causes an error so fix it by replacing it with <Route path="/register" element={<Register />} /> which is the version 6 format. Note route components should be rendered as JSX, not a reference to the component on the element prop. This is a breaking point between versions 5 and 6 of react-router-dom. Note also that Route components also no longer take an exact prop, they are now always exactly matched. practical issue

  • Incase you used <Switch></Switch> replace it with <Routes></Routes> and Wrap your route above in Routes which act as a parent for all the individual routes that will be created in your app. Route is used to create a single route. It takes in two attributes: path, which specifies the URL path of the desired component and element which specifies the component the route should render
  • Now in your nav tag or home screen file add <Link to="register">Register</Link> just like in HTML we have the <a> tag, in react we have the <Link></Link> component and its also imported from react-router-dom

Wrap Up

I hope this helped if it didn't then i think you are a beginner and you should learn more about react, this is to help the developers who have bug issues on the routes rendering. Reach out if you have any queries I'll be glad to help even if you're starting out on react and want a mentor. see you on the next.