I am doing a nested routers layout. I have a parent component that needs to render a list of N children. Additionally, I want to pass a function (id: string) => Observable<X>
from parent to child. Currently, I am doing:
// parent.tsx
function getStream(id: string): Observable<X>; // assume exists
function Parent() {
const child_links = children_data.map(child_data => (
<Link
to={...}
state={{ child_data, getStream }}
/>
));
...
// return some output with `child_links` embedded
}
// child.tsx
import { useLocation } from 'react-router';
function Child() {
const location = useLocation();
// The issue I am facing:
// returns { child_data: {...} } if I choose to omit `getStream` in `Parent`;
// returns `null` when `getStream` included; expected `getStream` to exist and be function I passed
console.log(location.state);
// some arbitrary rendering
}
//index.tsx, where Router defined:
ReactDOM.render(
<div>
<BrowserRouter>
<Routes>
<Route path='/' element={<Parent />}>
<Route path='children/:child_id' element={<Child />} />
</Route>
</Routes>
</BrowserRouter>
</div>,
document.getElementById('root')
);
Other ridiculous things I have tried:
- Wrapping the function in an object, passed through constructor. Effect: causes same
null
state problem. - Wrapping the function in an object, as a method. Effect: does not cause
null
state, but the associated property ofstate
ends up just being an empty object. this tells me that react-router is likely doing less-than-smart hash object cloning.
Things I think would be better avoided:
- Just creating a static controller object that serves up the
Observable
- Using the
Context
system fromreact
Am I abusing state
here? If Links
are to be used in a nest router setting, am I expected not to share upstream state with downstream components?
Thanks!
id
in route state for the child to invokegetStream
with.