How To Fix “Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’”?
Are you having problems with the issue “Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’“? How to fix it? In today’s article, I will provide solutions for you to solve the issues. Please follow the below steps to get the problem resolved now
How did “Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’” occur?
Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’
When you work with ReactJS, you may get the issue Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’. Don’t worry, we are here to provide you solutions in order to resolve your problem.
How to fix “Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’”?
To fix the attempted import error, ‘Switch is not exported from react-router-dom’. First, you need to uninstall react-router-dom using this command: npm uninstall react-router-dom . Next, install 5.2.0 using this command: npm install [email protected] .
Solution 1: Replace the switch with routes
If you are using ReactRouter-dom V6+, then Switch will be replaced by Routes. You need to import Routes first.
Before
import { Switch, Route } from "react-router-dom";
# Working In Smaller than v6
import { Routes ,Route } from 'react-router-dom'; # Working in v6 And Above
You also need to update the Route declaration
<Route path="/" component={Home} />
To
<Route path='/home' element={<Home/>} />
You will now be able to correct your error.
Here’s a V6 example.
import React from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import { Home } from "./app";
import { Login, Register } from "./auth";
const R: React.FC = () => {
return (
<Router>
<Routes>
<Route path="/login" caseSensitive={false} element={<Login />} />
<Route path="/register" caseSensitive={false} element={<Register />} />
<Route path="/" caseSensitive={false} element={<Home />} />
</Routes>
</Router>
);
};
export default R;
Solution 2: Upgrade react-router-dom
Simply downgrade react-router-dom from 5.2.0 . Then, first of all, uinstall react-router-dom with the help of This Command.
npm uninstall react-router-dom
With the help of this command, install 5.2.0
npm install [email protected]
Now, your error must be fixed.
This is the v6.*
example.
import React from "react";
import { BrowserRouter as Router, Route, Switch} from "react-router-dom";
import { Home } from "./app";
import { Login, Register } from "./auth";
const R: React.FC = () => {
return (
<Router>
<Switch>
<Route path="/login">
<Login />
</Route>
<Route path="/register">
<Register/>
</Route>
<Route path="/">
<Home/>
</Route>
</Switch>
</Router>
);
};
export default R;
Final words
The above are useful solutions that can help you fix “Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’” problem, if you can’t solve it well. Please leave a message.