If we are encountering an “Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’” message, it’s likely because we are trying to import the Switch component from react-router-dom, but it doesn’t exist.
Starting from React Router v6, Switch has been removed, and its functionality has been integrated into the Routes component. To achieve the same functionality as Switch from React Router v5 in React Router v6, weneed to use the Routes component with the element prop.
Here’s how we can refactor our code:
In React Router v5 we write
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
<Router>
<Switch>
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route path="/" component={Home} />
</Switch>
</Router>
);
}
Using React Router v6 we write
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
function App() {
return (
<Router>
<Routes>
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="/" element={<Home />} />
</Routes>
</Router>
);
}
In this example, the Routes component is used instead of Switch, and each Route component includes the element prop, which specifies the component to render for that route. Make sure our adjust our code accordingly based on our React Router version.