Trying to create a minimalist React Application using CDN to test React-router-dom. The below code works fine:
<html>
<head>
<meta charset='UTF-8'>
<script src="https://unpkg.com/react@latest/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@latest/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src='https://unpkg.com/[email protected]/umd/react-router-dom.min.js'></script>
</head>
<body>
<div id='root'></div>
<script type='text/babel'>
const Link = ReactRouterDOM.Link;
const Route = ReactRouterDOM.Route;
const Router = ReactRouterDOM.BrowserRouter;
function App(){
return (
<Router>
<nav>
<br/><Link to="/">TO HOME</Link>
<br/><Link to="/a">TO A</Link>
<br/><Link to="/b">TO B</Link>
</nav>
<Route path="/" exact component={()=><h1>Home</h1>} />
<Route path="/a" component={()=><h1>A</h1>} />
<Route path="/b" component={()=><h1>B</h1>} />
< / Router>
);}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
</script>
</body>
</html>
However, when I switch to the latest version of react-router-dom 6.17.0
<script src="https://unpkg.com/[email protected]/dist/umd/react-router-dom.development.js"></script>
I get an error:
index.tsx:1858 Uncaught TypeError: Cannot read properties of undefined (reading 'Route')
at Object.get [as Route] (index.tsx:1858:1)
at <anonymous>:4:28
Also, I am checking the exports in the CDN link and I don’t see Route being exported, while it is in the earlier version. Should this be done differently in version 6.17 of react-router-dom.
2
Answers
Try to import the BrowserRouter, Link, and Route elements from react-router-dom and use them in the code accordingly.
The Route component from version 5 is now replaced with the Route element in version 6.
I’m not exactly sure why, but adding other various "missing dependencies" appears to get the React-Router v6 code working for the use case.
[email protected]
: https://unpkg.com/[email protected]/dist/umd/react-router.development.js@remix/[email protected]
: https://unpkg.com/@remix-run/[email protected]/dist/router.umd.min.jsThe
Route
component is able to be imported now. Also import theRoutes
component as it replaced the React-Router v5Switch
component and handles route matching/rendering.Route
directly wraps a group ofRoute
components.