0

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

Chloe Sun
  • 111
  • 1
  • 6

2 Answers2

1

I finally figure out this issue:

ComponentA is wrapped with HOC, and by adding {...this.props} to ComposedComponent, enter image description here enter image description here

ComponentA can access the url params from this.props

Please refer this issue Passing React context through an HOC to a wrapped component

Chloe Sun
  • 111
  • 1
  • 6
0

I'm not sure it was working at first.

To access the param value, you have to do it this way :

const { match } = props;
const { params } = match;
const { id } = params;

You might need to wrap your component into withRouter(...)

import { withRouter } from "react-router-dom";
class MyComp extends PureComponent {...}
export default withRouter(MyComp);