I am trying to do this in a single html page. I first use unpkg.com to import the required things such as React and React-router-dom. If I use simple React staff, the page can load. Then I am trying to use React-router-dom, I add the script in the head tag and create a simple mydiv7. It shows an error message. Please help me see what is wrong with this code.
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="https://unpkg.com/react-router-dom/umd/react-router-dom.development.js" crossorigin></script>
</head>
<body>
<div id="mydiv7"></div>
<script type="text/babel">
const Layout = () => {
return (
<>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/blogs">Blogs</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
<Outlet />
</>
)
};
const Home = () => {
return <h1>Home</h1>;
};
const Blogs = () => {
return <h1>Blog Articles</h1>;
};
const Contact = () => {
return <h1>Contact Me</h1>;
};
const NoPage = () => {
return <h1>404</h1>;
};
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="blogs" element={<Blogs />} />
<Route path="*" element={<NoPage />} />
</Route>
</Routes>
</BrowserRouter>
);
}
ReactDOM.render(<App />, document.getElementById('mydiv7'));
</script>
</body>
</html>
CodePudding user response:
You need to import BrowserRouter according with documentation. You can import with cdn using referenfes to window, like this.
const BrowserRouter = window.ReactRouterDOM.BrowserRouter;
CodePudding user response:
I believe somewhere in your script you need to reference the react router package like you do with React
for react
and ReactDOM
for react-dom
.
From what I can tell react-router-dom
is exported as ReactRouterDOM
.
Load the CDN links for the specific version of react-router-dom
being used. Current is v6.1.1.
<!-- Load React Router and React Router DOM --> <script src="https://unpkg.com/[email protected]/umd/react-router.development.js" crossorigin></script> <script src="https://unpkg.com/[email protected]/umd/react-router-dom.development.js" crossorigin></script>
const BrowserRouter = ReactRouterDOM.BrowserRouter;
const Routes = ReactRouterDOM.Routes;
const Route = ReactRouterDOM.Route;
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="blogs" element={<Blogs />} />
<Route path="*" element={<NoPage />} />
</Route>
</Routes>
</BrowserRouter>
);
}