Ben
Ben

Reputation: 16641

Passing state to child component

In the following React Native scenario, how can I pass the variable userId from the 'parent' component to the 'child' component?

I have a 'parent' component like so:

export class UserProfileScreen extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            userId: 123,
        }
    }

    render() {
        return(
            <View>
                <UserIntro />
            </View>
        )
    }
}

And a 'child' component like so:

export class UserIntro extends React.Component {

    render() {
        return(
            <View>
                <Text>Introduction for user {userId}</Text>
            </View>
        )
    }
}

Upvotes: 0

Views: 1344

Answers (2)

Rajesh N
Rajesh N

Reputation: 6673

You can pass anything(JSON object,JSON Array,simple arrays,float and even function etc) from parent to child using props. There is no limit of props number.

you can execute parent function from child as well using props

export class UserProfileScreen extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      userId: 123
    };
  }

  getUpdatedUserID = updatedId => {
    this.setState({userId:updatedId});
    alert(updatedId);
  };

  render() {
    return (
      <View>
        <UserIntro id={this.state.userId} getUpdatedUserID={this.getUpdatedUserID} />
      </View>
    );
  }
}

export class UserIntro extends React.Component {


  updateUserId=()=>
  {
    this.props.getUpdatedUserID((int)(this.props.id)+1);
  }

  render() {
    return (
      <View>
        <Text>Introduction for user {this.props.id}</Text>
        <Button onPress={this.updateUserId}  />

      </View>
    );
  }
}

Upvotes: 1

Buwaneka Sirinath
Buwaneka Sirinath

Reputation: 115

export class UserProfileScreen extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            userId: 123,
        }
    }

    render() {
        return(
            <View>
                <UserIntro id={this.state.userId} />
            </View>
        )
    }
}


export class UserIntro extends React.Component {

    render() {
        return(
            <View>
                <Text>Introduction for user {this.props.id}</Text>
            </View>
        )
    }
}

Upvotes: 2

Related Questions