Martin Blore
Martin Blore

Reputation: 2195

How to set state on child component?

I have a component that renders out a list of buttons, lets call this 'ButtonList'. When one of the buttons is clicked, the event is bubbled up like so:

<ButtonList onButtonPressed={(mins) => { console.log(mins); }} />

In response to this, I want to hide that ButtonList and show another component that is currently hidden. The ButtonList has some state such as "state { visible: true }" that I want to toggle that stops it rendering. How do I make a call to toggle the state of that ButtonList and then also call my other component in this view to also toggle its visible state to show?

Thanks.

Upvotes: 1

Views: 843

Answers (1)

Travis White
Travis White

Reputation: 1977

  swappingComponentsExample = () => {
    return (
      <View>
        {this.state.showButtonList ? (
          <ButtonList
            onButtonPressed={mins => {
              this.setState({showButtonList: false});
              console.log(mins);
            }}
          />
        ) : (
          <OtherComponent />
        )}
      </View>
    );
  };

  // Renders both components but passes style override to hide the object
  // ButtonList/OtherComponent are not destroyed and recreated using this method
  hidingExample = () => {
    return (
      <View>
        <ButtonList
          onButtonPressed={mins => {
            this.setState({showButtonList: false});
            console.log(mins);
          }}
          style={!this.state.showButtonList && {display: 'none'}}
        />

        <OtherComponent
          style={this.state.showButtonList && {display: 'none'}}
        />
      </View>
    );
  };

Upvotes: 1

Related Questions