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>
}
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>;
}
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.