CraZyDroiD
CraZyDroiD

Reputation: 7127

Passing states between components

I'm trying to do some actions based on the states of another component. I have a select box and i'm changing the state when the user changes the options.

<div className="post_privacy_div float_left">

    <select className="review_privacy_select" onChange={this.commentOption}>

        <option value="Comments with filter">Comments with filter</option>

        <option value="Enable comments">Enable all comments</option>

        <option value="Disable comments">Disable all comments</option>

    </select>
</div>

Function

commentOption(e) {

        this.setState({selectValue: e.target.value});
}

So the state changing is successfully done. Now i want to pass this state into another component.How can i do it?

Basically i'm trying to do this but in another component

   if (this.state.selectValue === 'Enable comments') {

                this.setState({

                    pendingcomment: !this.state.pendingcomment,

                })

            } else if (this.state.selectValue === 'Disable comments') {

                this.setState({

                    pendingcomment: false,
                    allcomment: false,

                })

            } else {

                this.setState({

                    pendingcomment: true,
                    allcomment: true,

                })

            }

Upvotes: 2

Views: 2857

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104529

In that case maintain the value in parent component and pass that value and a function from parent to Child1 (passing a function is required to change the value in parent component), pass value to Child2.

Check this working snippet:

class Parent extends React.Component {
    constructor(){
       super();
       this.state = { value: null}
       this.change = this.change.bind(this)
    }
    
    change(value){
       this.setState({value})
    }
    
    render(){
       return(
          <div>
             <Child1 value={this.state.value} change={this.change}/>
             <Child2 value={this.state.value}/>
          </div>
       )
    }      
}

class Child1 extends React.Component {
   render(){
      return(
         <div>
           In Child1:
           <select value={this.props.value} onChange={(e) => this.props.change(e.target.value)}>
              <option value='1'>1</option>
              <option value='2'>2</option>
              <option value='3'>3</option>
           </select>
         </div>
      )
   }
}

class Child2 extends React.Component {
   render(){
      return(
         <div>In Child2: {this.props.value} </div>
      )
   }
}

ReactDOM.render(<Parent/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

Upvotes: 3

Related Questions