Reputation: 11424
I have the following code in a React render function:
<div>
<InnerBox>
<div>Box 1</div>
<HiddenBox />
</InnerBox>
<InnerBox>
<div>Box 2</div>
<HiddenBox />
</InnerBox>
<InnerBox>
<div>Box 3</div>
<HiddenBox />
</InnerBox>
</div>
I would like each of the <HiddenBox />
elements to be hidden until the <InnerBox>
element is clicked on. Any other child elements of <InnerBox>
should be displayed at all times.
I currently have the following function in my InnerBox
class:
handleClick(){
this.setState({
button_state: "clicked"
})
}
And my render function of the InnerBox
class looks something like this:
return (
<div onClick={this.handleClick.bind(this)}>{this.props.children}</div>
)
However, I am a bit confused as to where exactly the code would go to toggle the display of the HiddenBox
element for the specific InnerBox
that was clicked on.
How do I go about doing this?
Upvotes: 2
Views: 9349
Reputation: 6286
To toggle hide and show.
export default class InnerBox extends React.Component {
state = {
buttonClicked: false
};
handleClick = () => {
this.setState({
buttonClicked: !this.state.buttonClicked
});
};
render() {
return (
<div onClick={this.handleClick}>
{this.props.children}
{this.state.buttonClicked && <HiddenBox />}
</div>
);
}
}
Upvotes: 3
Reputation: 30390
If I understand correctly, then you could resolve this by updating the rendering of <InnerBox/>
in this way:
<div>
<InnerBox>
<div>Box 1</div>
</InnerBox>
<InnerBox>
<div>Box 2</div>
</InnerBox>
<InnerBox>
<div>Box 3</div>
</InnerBox>
</div>
You could then update the render()
function of <InnerBox/>
like so:
render() {
const { button_state } = this.state;
const isButtonStateClicked = button_state === 'clicked';
return (<div onClick={this.handleClick.bind(this)}>
{ this.props.children }
{ isButtonStateClicked && <HiddenBox /> }
</div>)
}
Finally, you'd update handdleClick()
in this way to achieve to hide/show toggle behaviour:
handleClick(){
this.setState({
button_state: this.state.button_state === 'clicked' : '' : 'clicked'
})
}
Upvotes: 1