Reputation: 2657
I trying to change my state in another component. I have passed the state by props
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
isOpen: false
};
}
<MobileContent isOpen={this.state.isOpen} />
In my MobileContent component i want to change the state when i click on the element.
class MobileContent extends Component {
render() {
if (this.props.isOpen) {
return (
<Grid fluid>
<div className="mobileContent">
<Row center="xs">
<Col xs={12}>
<span className="button">Hello, world!</span>
<span className="close" onClick={this.handleClick} >X</span>
</Col>
</Row>
</div>
</Grid>
);
}
return null;
}
}
export default MobileContent;
Thanks for the help !!
Upvotes: 1
Views: 59
Reputation: 85161
If you want the Child component to notify the parent, then you should pass an additional prop down to the child which is a function. The child can then call that. So in the parent:
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
isOpen: false
};
}
<MobileContent isOpen={this.state.isOpen} onClose={this.handleClick}/>
And in the child:
render() {
if (this.props.isOpen) {
return (
<Grid fluid>
<div className="mobileContent">
<Row center="xs">
<Col xs={12}>
<span className="button">Hello, world!</span>
<span className="close" onClick={this.props.onClose}>X</span>
</Col>
</Row>
</div>
</Grid>
);
}
return null;
}
Upvotes: 2