I am trying to make a portfolio website (using React codesandbox) with multiple pages that talk about me, and I encountered an error message stating "Element type is invalid" in my React application. This error typically occurs when trying to render a component that is either not defined or not exported properly.
In my code snippet, the error occurs in the App component when rendering routes using React Router. I don't know how I can successfully debug this error. Can someone help me understand what had happened and what can I do to correct this error? Thank you for taking your time on this.
Screenshot of error message in codesandbox
App.js
// App.jsx
import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Landing from "./pages/landing";
import List from "./pages/toc";
import About from "./pages/about";
import "./styles.css";
const App = () => {
return (
<Router>
<div className="app">
<Switch>
<Route exact path="/" component={Landing} />
<Route path="/table-of-contents" component={List} />
<Route path="/about" component={About} />
</Switch>
</div>
</Router>
);
};
export default App;
I have tried to debug which Route is messing up the code but it comes up that the Route itself is flawed. I don't know the exact steps to accomplish the react-router-dom page creation.
P.S.: Here is the link to a forked codesandbox page:
Odd, normally you should have seen an error stating something to the effect of "Switch not exported from
react-router-dom, these are the named exports ....". Your code is the older React-Router-DOM v4/5 syntax but you have specified React-Router-DOM v6 as a dependency.Using React-Router-DOM v4/5
If you want to continue using your current code then you'll need to downgrade the
react-router-domdependency.npm uninstall --save react-router-domnpm install --save react-router-dom@5Using React-Router-DOM v6
If you want to use the current version of
react-router-domthen you'll need to fix several breaking changes.Switchcomponent, it was replaced by theRoutescomponent.Routecomponent API was changed a bit as well, there is no longer anycomponent(andrenderandchildrenfunction prop), replaced by a singleelementprop taking aReact.ReactNode, a.k.a. JSX, value.useHistoryhook was removed, replaced by auseNavigatehook that returns anavigatefunction instead of thehistoryobject.Update
Appto import and use theRoutescomponent. Render the routed content correctly on theelementprop.Replace the
useHistoryhook with theuseNavigatehook in the routed components.Landing
Toc
You may want to read through the Upgrading from v5 migration guide for complete details for all the breaking changes in v6, and review the Main Concepts for a high-level overview of the new features.