I am using react router dom v6 how can I access the context in a nested route in the second child
<Routs>
<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>
}
CodePudding user response:
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);
CodePudding user response:
Recall that context consumers consume the context value of the closest context provider above them in the ReactTree. The middle child should pass the context value through to the Outlet
it is rendering.
const Parent = () => {
const myContext = { someData: "hello world" };
return <Outlet context={myContext} />;
};
const Child = () => {
const context = useOutletContext();
return <Outlet context={context} />;
};
const ChildSecond = () => {
const { someData } = useOutletContext();
return <div>{someData}</div>;
};
Also, be sure to render at least one path on "/".
<Router>
<Routes>
<Route element={<Parent />}>
<Route element={<Child />}>
<Route path="/" element={<ChildSecond />} />
</Route>
</Route>
</Routes>
</Router>