0

I am trying to pass a prop to a child component in react but its not showing up at all in props when I console log it. Even the key things don't show up. Any help on this will be appreciated.

export default class Child extends Component {

  constructor(props) {
        super(props);
        console.log(props)
    }

  render() {
    console.log(this.props)
    return (
        <div>
          Test
        </div>
    );
  }
}


class Parent extends Component {
  constructor(props) {
      super(props);
  }

  render() {
    return (
      <div>
        <Router>
          <div>
            <Route path='/testing' things="yes" component={Child} />
          </div>
        </Router>
      </div>
    );
  }
}
}

const connectedParent = connect()(Parent);
export { connectedParent as Parent };
HeelMega
  • 458
  • 8
  • 23

1 Answers1

1

In your Parent component replace Route with following,

<Route
  path='/testing'
  render={(props) => <Child {...props} things="yes" />}
/>

Let me know if it works.

Explanation: when you were using <Route path='/testing' things="yes" component={Child} />, you were not passing the props to Child component but to the Route component and it was ignoring it.

One more method to pass props to Child component in Route is:

<Route
  path='/testing'
  component={() => <Child things="yes" />}
/>

but with method you would lose Route props like location, history and other of it's props and also according to docs:

When you use the component props, the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component attribute, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component.

So we are left with the method I suggested, i.e

<Route
      path='/testing'
      render={(props) => <Child {...props} things="yes" />}
    />

here you are passing props like things to the Child component itself and not the route and also render method of Route provides Route props. So always remember to pass it props as {...props}, so that you can access Route props in Child component and you'll not face any issues while Routing.

Farid Ansari
  • 813
  • 5
  • 7