It has been a while since I've worked with React-Router and the first time with v6. My applications is using:
I've attempted the following:
react-router
tutorial and applied it to my applicationI've been taking a step by step approach to the application where I test each change before I go onto the next. It appears my routing is correct as I tested it by typing in the routes as the URL. However, when I attempt to add Link
, I'm getting the out of context error. I know I'm missing something simple but I'm just not seeing it. Here is the code with imports omitted for brevity.
index.jsx
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<ThemeProvider theme={theme}>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<App />
</ThemeProvider>
</React.StrictMode>
)
app.jsx
const router = createBrowserRouter([
{
path: "/",
element: "",
errorElement: <ErrorPage />,
children: [
{
path: "/about",
element: <About />,
},
{
path: "/products",
element: <Products />,
},
{
path: "/",
element: <Home />,
},
]
},
]);
function App() {
const [count, setCount] = useState(0)
return (
<><HeaderBar />
<RouterProvider router={router}>
<div>
<Outlet />
</div>
</div>
</RouterProvider></>
)
}
export default App
HeaderBar.jsx (only failing element is shown for brevity)
<Button
key={page.text}
onClick={handleCloseNavMenu}
sx={{ my: 2, color: 'white', display: 'block' }}
component={Link}
to={page.target}
>
{page.text}
</Button>
I have attempted to create the context by trying to wrap <BrowserRouter>
around various components, but receive error messages about having 2 routers in my application.
The issue here is that the HeaderBar
is rendered outside a router, e.g. any routing context, so the Link
component doesn't work. Move it into the router.
The RouterProvider
component also doesn't consume any children
prop, so the "child" JSX is completely ignored and should be removed.
Example using a layout route component to render the header and Outlet
for the nested routes:
const AppLayout = () => (
<>
<HeaderBar />
<Outlet />
</>
);
const router = createBrowserRouter([
{
path: "/",
element: <AppLayout />,
errorElement: <ErrorPage />,
children: [
{
path: "/about",
element: <About />,
},
{
path: "/products",
element: <Products />,
},
{
path: "/",
element: <Home />,
},
]
},
]);
function App() {
const [count, setCount] = useState(0)
return <RouterProvider router={router} />;
}
export default App;