4

I have a simple component who show element onClick:

    class MyComponent extends React.Component {

       state = {
        isVisible : false
       }

     render() {
      const { isVisble } = this.state
      return(
      <div>
       {isVisble ? 
        <div onClick={() => this.setState({isVisble: false})}>Hide</div> : 
        <div onClick={() => this.setState({isVisble: true})}>Show</div>}
      </div>
     )
    }
}

I use this component three times in other component :

class MySuperComponent extends React.Component {     
 render() {
  return(
  <div>
   <MyComponent /> 
   <MyComponent /> 
   <MyComponent /> 
  </div>
  )}
}

I need to pass isVisible at false for all other component if one of have isVisible to true

How to do that ?

Thanks

Lionel B
  • 1,172
  • 2
  • 9
  • 24

2 Answers2

3

You should have your component controlled, so move isVisble to props and and then assign it from MySuperComponent.

Also pass MyComponent a callback so it can inform the parent if it wants to change the state.

You'd want some data structure to store that states.

https://codepen.io/mazhuravlev/pen/qxRGzE

class MySuperComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {children: [true, true, true]};
        this.toggle = this.toggle.bind(this);
    }

    render() {
        return (
            <div>
                {this.state.children.map((v, i) => <MyComponent visible={v} toggle={() => this.toggle(i)}/>)}
            </div>
        )
    }

    toggle(index) {
        this.setState({children: this.state.children.map((v, i) => i !== index)});
    }
}

class MyComponent extends React.Component {
    render() {
        const text = this.props.visible ? 'visible' : 'hidden';
        return (<div onClick={this.props.toggle}>{text}</div>);
    }
}


React.render(<MySuperComponent/>, document.getElementById('app'));
Mikhail Zhuravlev
  • 969
  • 2
  • 10
  • 22
0

You can check your code here, is this what you want. example