How to use reach router with React Context API?
I use reach router like this below before and it works fine
.....
<Router>
<ComponentA path="/:id">
<ComponentB path="/">
<Router>
....
I decided to refactor my code with context , and the code is refactored to something like this:
<GlobalContextProvider>
<GlobalContext.Consumer>
{( context) =>{
return(
.....
<Router>
<ComponentA path="/:id">
<ComponentB path="/">
<Router>
....
}
After the refactor, the ComponentA is not working properly, as the url param prop id is not passed
In the ComponentA.js , test like this:
componentDidMount() {
const { id } = this.props;
console.log(id); // return undefined
}
Also when I console.log(this.props) , it returns the same result as this.context
Can someone help me understand why this is happening? How to refactor with context properly?
Thanks a lot
@ryanflorence Could you please take a look at my issue, I've stuck with this one for a while. Thank you very much!
Hey @chloesun sorry for the delay.
I get what you're trying to do, though I'm not seeing how you're wanting to use context to pass in the id.
Is there a repo or codesandbox I could look at? I'd be happy to get you on the right track 馃槃
@mtliendo thanks for your reply! I wrapped the entire app under the GlobalContext.consumer, but I still want to pass the url params id as a prop just like this example https://reach.tech/router/example/url-params.
Now for Component A, I can't access id from this.props, and when I try to console.log(this.props), it logs the same result as this.context. Sorry, I don't have a public repo for now.
A bit tough to know exactly what you're looking for, but I hope this helps 馃槂 In this example, the id can still be access on props, while a lower component can still access context set on the provider:
Hope that helps out, I'll go ahead and close, though feel free to post if there's something else going on.
Thanks @mtliendo , my Component that uses url params as prop is deeply nested in the app, I will try to refactor my code.
I finally figure out this issue:
ComponentA is wrapped with HOC, and by adding {...this.props} to ComposedComponent,
ComponentAcan access the url params fromthis.props
Please refer this issue https://stackoverflow.com/questions/45873414/passing-react-context-through-an-hoc-to-a-wrapped-component