So I’m just trying to use react-router-dom
‘s Link
component and whether it’s in my main project or a recreate, it just causes the browser to go blank and throws a console error of "react__WEBPACK_IMPORTED_MODULE_0__.useContext(...) is null"
.
The homepage is
import React from 'react';
import Nav from './Pages/Nav';
import {
createBrowserRouter,
RouterProvider
} from 'react-router-dom';
import Home from './Pages/Home';
import Gallery from './Pages/Gallery';
const router = createBrowserRouter([
{
path: "/",
element: <Home />
},
{
path: "/Gallery",
element: <Gallery />
},
])
function App() {
return (
<div>
<Nav />
<RouterProvider router={router} />
</div>
);
}
export default App;
and the link page is
import { Link } from 'react-router-dom';
const Nav = () => {
return (
<nav>
<ul style={{ listStyle: "none" }}>
<li style={{ cursor: "pointer" }}>
<Link to='/'>Home</Link>
</li>
<li style={{ cursor: "pointer" }}>
<Link to='/Gallery'>Gallery</Link>
</li>
</ul>
</nav>
)
}
export default Nav
Commenting out the Link
components causes everything to work ok again.
5
Answers
I am not 100% sure if my suggestion will solve the issue but for what it’s worth here is what you can try:
1 – Remove the space between the name and closing tag of the components like so:
2 – You can remove the div element and wrap everything with BrowserRouter which you can import from "react-router-dom";
Hope it works.
Every component outside the router provider is outside the scope of react-router primitives so it fails because it cant perform the needed actions. You need something like this:
This way you can go to /nav and Links will work. Anyway, the best way is to add to the other components not to have a navigation page. So you have to include the nav in every element of your router.
The
Nav
component is outside theRouterProvider
context, you can fix it by changing the/
path to a<Root>
component and rendering the<Nav>
and an<Outlet>
, something like this:In
App.js
The
Nav
component is rendered outside the routing context provided by the router component,RouterProvider
in this case. All components that need to access the provided routing context necessarily need to be rendered under the provider in the ReactTree. In this case you’ll need to create a layout route that rendersNav
and anOutlet
for nested routes to render their content into.Example:
Another way would be using BrowserRouter, Routes and Route like this: