'how to pass outlet context to nested route in react router v6
I am using react router dom v6 how can I access the context in a nested route in the second child
<Routes>
<Route element={<Parent/>}>
<Route element={<Child/>}>
<Route element={<ChildSecond/>}/>
</Route>
<Route>
</Routes>
I passed a context to Outlet in Parent Component I wanna access it in ChildSecond with out passing it again in Child component Outlet
expected code
Parent Component:
const Parent = ()=>{
const myContext = {someData:'hello world'}
return <Outlet context={myContext}/>
}
Child Component:
const Child = ()=><Outlet/>
ChildSecond component
import {useOutletContext} from 'react-router-dom'
const ChildSecond = ()=>{
const {someData} = useOutletContext()
return <div>someData</div>
}
Solution 1:[1]
You could define a context in the main component and provide it to the whole application:
export const GlobalContext = React.createContext();
...
<GlobalContext.Provider
value={{someData: 'hello world'}}>
<Routs>
<Route element={<Parent/>}>
<Route element={<Child/>}>
<Route element={<ChildSecond/>}/>
</Route>
<Route>
</Routes>
</GlobalContext.Provider>
Then retrieve the data anywhere in your application with:
import { useContext } from 'react'
import { GlobalContext } from '/path/to/main/file';
...
const { someData } = useContext(GlobalContext);
Solution 2:[2]
As of v6.3.0. react-router's useOutletContext() only works in the immediate child component. If you really don't want to create your own context, you can easily forward the outlet context on like so:
import React from 'react';
import { Routes, Route, Outlet, useOutletContext } from 'react-router-dom';
export default function App() {
return (
<Routes>
<Route element={<Grandparent />}>
<Route element={<Parent />}>
<Route index element={<Child />} />
</Route>
</Route>
</Routes>
);
}
function Grandparent() {
return (
<main>
<Outlet context={{ someData: 'hello world' }} />
</main>
);
}
function Parent() {
return <Outlet context={useOutletContext()} />;
}
function Child() {
const { someData } = useOutletContext<{ someData: string }>();
return <p>{someData}</p>;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lpizzinidev |
| Solution 2 | followben |
