0

Suppose I have a class called HomeScreen and it has Location, and Person as Components:

HomeScreen contains the component Location:

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

    export default class HomeScreen extends Component {
    ...
      render() {
        const { navigate } = this.props.navigation;
        return (
                 <Location 
                    navigator={this.props.navigation}
                    ></Location>
                 <Person location={this.state.location} />
        )}
    }

Location Class:

export default class LocationSelector extends Component{
        constructor(props){
        super(props);
        this.state = {
            location: '',
            region: '',
        }
    }

   onSelect = fullLocation => {
    var location = fullLocation.location;
    this.setState({location: location});
   }

    render(){
        return (
                  <View>
                     <TouchableOpacity
                     onPress={() => this.props.navigator.navigate('Location',{ onSelect: this.onSelect })}>
                     </TouchableOpacity>
                   </View>
             )
   }
}

Person Class:

class  Person extends Component{

  constructor(props){
    super(props);
    this.state={
      distance: 2,
    }
  }

    static defaultProps = {
      location:  '',
    }

  componentWillReceiveProps (nextProps) {
    this.setState({distance: 4});
  }

  render () {
    return <Text>Person: {this.props.location} distance : {this.state.distance}</Text>;
  }
}

Description of the codes: explaining the long codes

HomeScreen(state=> location) is the first class to be seen, from here Location(state=>location) component is added . Now in Location class its location state is initialised . And in Person(prop=>location, state=> distance) class I need that value to re-render the Person component to provide a state called distance dynamically.

My question is how can I get the value from Location component and set it to HomeScreen state and pass the same value to Person class ?

I am using componentWillReceiveProps() to reload the Person Component .

Subhajit
  • 876
  • 3
  • 17
  • 37

0 Answers0