Skip to content Skip to sidebar Skip to footer

Trouble Passing Props To Componentdidmount In Child Component (react)

I'm having issues passing a prop to a componentDidMount() call in a child component on my React application. In my App.js I am passing props via Router like below: App.js class App

Solution 1:

In the constructor you should reference props, not this.props:

location: props.city

Solution 2:

        <Route path="/" exact render = {() => <Projections city={this.state.city} {...this.props} />} />

Try passing rest of props in route

this is because you assigned props in constructor that time it may or may not receive actual value. And it gets called only once in a component lifecycle. You can use componentWillReceiveProps to get props whenever it receive and update state accordingly.

Inside Projections.js

UNSAFE_componentWillReceiveProps(nextProps){
   if(nextProps.city){
     this.setState({location:nextProps.city})
   }
}

Here is working codesand

Post a Comment for "Trouble Passing Props To Componentdidmount In Child Component (react)"