I'm trying to make reusable toggle function.
Component initial state:
constructor(props) {
super(props);
this.state = {
collapseFirst: false,
collapseSecond: false
};
}
Toggle function (it should change true/false state based on collapse target clicked):
handleToggle = e => {
const collapseItem = e.target.getAttribute('data-control');
this.setState({
[collapseItem]: !this.state.collapseItem
});
};
Rendered elements (using Reactstrap Collapse component):
return (
<div>
<Button color="primary" onClick={this.props.toggle} data-control="collapseFirst">
First Collapse
</Button>
<Collapse isOpen={this.props.collapseFirst}>
<p>Some text</p>
</Collapse>
<Button color="primary" onClick={this.props.toggle} data-control="collapseSecond">
Second Collapse
</Button>
<Collapse isOpen={this.props.collapseSecond}>
<p>Some another text</p>
</Collapse>
</div>
);
The problem is that for some reason collapseItem returns expected data-control value but this.state.collapseItem is undefined.
What am I doing wrong?