Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: Passing props between components and componentWillMount() method

I'm using React Native 0.43. I've two components, named ParentComponent and ChildComponent. I want to pass some props from parent to child component. I'm using following code (abridged version) in parent component:

export default class ParentComponent extends Component {

  constructor(props) {
    super(props);

    this.state = {
      latitude: 34.7821,
    };
  }

  render() {
    return (
      <View>
        <ChildComponent latitude={this.state.latitude} />
      </View>
    );
  }

}

My child component is as following:

export default class ChildComponent extends Component {

  constructor(props) {
    super(props);

    this.state = {
      latitude: props.latitude,
    };
  }

  componentWillMount() {
    console.log('Before Mount: ' + this.state.latitude)
  }

  render() {
    return (
        <Text>{'Mounted: ' + console.log(this.state.latitude)}</Text>
    );
  }
}

Now, my console shows following result:

2:14:12 AM: Before Mount: null

2:14:12 AM: Mounted: null

2:14:12 AM: Mounted: 34.7821

Now componentWillMount() in my original code has an API call to a web service which depends on the value of this.state.latitude which clearly is not been passed, at least on the first render. On second render, when this.state.latitude value become available, only the render() function executes, but i need this value in my componentWillMount() function.

What I'm doing wrong here?

like image 266
Faisal Khurshid Avatar asked Dec 08 '22 18:12

Faisal Khurshid


1 Answers

I was not able to receive props value in componentWillMount because this method only executes once, just before initial rendering. Since the props were not being passed from parent to child component on the first rendering, I solve the issue by using componentWillReceiveProps method in my child component. It receives the props on subsequent rendering and updates the original state in my child component. Which makes me able to access my state value. The code I use to solve is following:

  componentWillReceiveProps(nextProps) {
      // update original states
      this.setState({
        latitude: nextProps.latitude,
      });
  }
like image 160
Faisal Khurshid Avatar answered Dec 11 '22 09:12

Faisal Khurshid