SoFunction
Updated on 2025-04-07

Errors and solutions when using React-Router

Problem description

Problems that arise when configuring routing, the difference between Router5 and Router6

:38620 Uncaught Error: A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.
    at invariant (:38620:20)
    at Route (:39415:11)
    at renderWithHooks (:24114:22)
    at mountIndeterminateComponent (:28690:17)
    at beginWork (:30148:20)
    at (:12074:18)
    at (:12123:20)
    at invokeGuardedCallback (:12185:35)
    at beginWork$1 (:34989:11)
    at performUnitOfWork (:34163:16)

Cause analysis

The role of the Switch

  • Normally, path (path) and component (component) are one-to-one correspondence.
  • In the default route matching rule, if Switch is not used, all registered routes will match the path and all matching components will be displayed. The following code: If the input path is /home, the two components Home and Hotel will be displayed.
  • Switch can improve the matching efficiency of routes, and once matched, it will no longer continue to match downwards.
		 <Routes> 
                <Route path="/about" element={<About />}/>
                <Route path="/home" element={<Home />}/>
                <Route path="/home" element={<Hotel />}/>
              </Routes> 

Routes in Router6

Routes is used in Router6 instead of Switch, but the subtle difference is that there will be no errors if you do not use Switch in Router5.

However, if Routes is not used in Router6, the above error will be reported.

The reason for this modification needs to be learned? ?

Solution

In summary, of course, the solution is to add Routes

import React from "react";
import {BrowserRouter as Router, Routes, Route} from 'react-router-dom'
import Login from "./Login";
function Main(){
  return (
    <Router>
      <Routes>
       <Route path='/login' exact element={<Login/>} />
      </Routes>
    </Router>
  )
}
export default Main

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.