Home > Net >  React Router Dom upgrade error - Element type is invalid: expected a string
React Router Dom upgrade error - Element type is invalid: expected a string

Time:11-12

After installing the latest version v6 getting this error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

The code works well for lower versions but fails for version6.

Code: index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';

ReactDOM.render(
  <Router>
    <App />
  </Router>,

  document.getElementById('root')
);

App.js

import React from 'react';
import './style.css';
import { Switch, Route } from 'react-router-dom';
import Home from './Home';
let App = () => {
  return (
    <>
    
      <Switch>
        <Route path="/" component={Home} />
      </Switch>
    </>
  );
};

export default App;

Home.js

import React from 'react';

let Home = () => {
  return <h1>Home</h1>;
};

export default Home;

CodePudding user response:

In V6, React Router added some breaking changes & one of them is they replaced Switch with Routes. Also, instead of component={Home} it should be element={<Home/>}

CodePudding user response:

In v6, Switch is no longer supported use Routes instead. Use Element as attribute instead of component.

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