I am coming across Switch export error from react-router-dom

Viewed 30717

I am coming across the following error and cannot find a way out of it. Could anyone please help?

export 'Switch' (imported as 'Switch') was not found in 'react-router-dom' (possible exports: BrowserRouter, HashRouter, Link, MemoryRouter, NavLink, Navigate, Outlet, Route, Router, Routes, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, createRoutesFromChildren, createSearchParams, generatePath, matchPath, matchRoutes, renderMatches, resolvePath, unstable_HistoryRouter, useHref, useInRouterContext, useLinkClickHandler, useLocation, useMatch, useNavigate, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRoutes, useSearchParams)

8 Answers

Instead of using like this

      <Switch>
        <Route exact path="/">
          <Home />
        </Route>
        <Route path="/users">
          <Users />
        </Route>
      </Switch>

Use like this...

      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="users/*" element={<Users />} />
      </Routes>

Read this docs: https://reactrouter.com/docs/en/v6/upgrading/v5

Try this one. It worked nicely for me :)

To import

import {
  BrowserRouter as Router,
  Routes,
  Route, Redirect,Navigate
} from "react-router-dom";

Here is the way to implement your routes in App.Jsx file

const App = () => {
  const user = true;
  return (<Router>
    <Routes>
      <Route path="/" element={<Home />} />
    </Routes>
  </Router>);

You can import like this,

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

and then replace <Switch> and </Switch> with <Routes> and </Routes>

Example code is here,

<Router>
    <Navbar/>
    <Routes>
      <Route exact path="/" element={<Home />} />
      <Route exact path="/about" element={<About />} />
    </Routes>
</Router>

If you are using react-router-dom v6+, then Switch is replaced with Routes. So you need to simply import routes and you can use it here.

Before working in smaller than v6:

import { Switch, Route } from "react-router-dom";

Now, working in v6 And above

import { Routes ,Route } from 'react-router-dom'; 

Also You Need to update Route declaration

<Route path="/" component={Home} />

to

<Route path='/home' element={<Home/>} />

Now, Your error will be solved.

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

and use Routes insted of Switch

its work for this error and got exact solution..

latest version of react-router-dom does not need a "switch" and the structure is different. The code will look like this.

  <Routes>
    <Route path="/" element={<Home />} />
  </Routes>

is encapsul ated in and "exact" is not needed.

Related