logos_164
logos_164

Reputation: 786

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 extends Component {

state = {
    city: ""
}

componentDidMount() {
    this.setState({city: this.props.city});
}

render() {

    return (
        <div>
            <Route path="/" exact render = {() => <Projections city={this.state.city} />} />
            <Route path="/:id" component={FullPage} />
        </div>
    );
}

}

In my Projections.js I have the following:

Projections.js

constructor(props) {
        super(props);
           this.state = {
            location: this.props.city
        }
    }

    componentDidMount () {
        console.log(this.state.location);
console.log(this.props.city);

    }

console.log(this.state);' returns an empty string.console.log(this.props.city);` returns an empty string as well.

But I need to access the value of the city prop within componentDidMount(). console.log(this.props.city); within render() returns the prop, but not in componentDidMount()

Why is this and how do I return props within componentDidMount()?

Upvotes: 1

Views: 4970

Answers (2)

Revansiddh
Revansiddh

Reputation: 3062

        <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

Upvotes: 2

Alan Friedman
Alan Friedman

Reputation: 1610

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

location: props.city

Upvotes: 3

Related Questions