Reputation: 153
I have a reactstrap
Collapse
component that I'm trying to toggle
state
from an external Button
that sits within a loop of mapped items using custom state variables.
My question:
Why does it only open
and not toggle
the collapse
component when I have the state on my openCollapse
method to setState
to !state.collapse
?
My code:
// some_items.js (brief example)
// State
this.state = {
toggleCollapse: false
}
// my custom state variable that I want to have toggle
openCollapse(itemId) {
this.setState(state => ({
[`toggleCollapse-${itemId}`]: !state.collapse
}));
}
// mapped item with button trigger for toggling the collapse
<div key={item.id>
<Button
onClick={() => {
this.openCollapse(item.id);
}}
>
View Listed Item Info
</Button>
//
// Some extra content that belongs here in between..
//
<ItemInfoCollapse
show={this.state[`toggleCollapse-${item.id}`]}
item={item}
/>
</div>
// My item_collapse.js
class ItemInfoCollapse extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
collapse: false,
isOpen: this.props.show
};
}
componentWillReceiveProps(nextProps) {
this.setState({ isOpen: nextProps.show });
}
toggle = () => {
this.setState({ collapse: !this.state.collapse });
};
render() {
return (
<Collapse isOpen={this.state.isOpen} className={this.props.className}>
// Some JSX markup
</Collapse>
)
}
Upvotes: 0
Views: 100
Reputation: 652
What dictates whether your Collapse
component gets open or closed is based on the show
prop that you are passing into it from your parent component.
It appears you have everything set up correctly, with the exception of your state variable that you're using in your openToggle
function - !state.collapse
. I don't see the collapse
variable anywhere which means it's undefined so it's actually running !undefined
which always evaluates to true (you can test this in a browser console).
I think what you mean is !state[
toggleCollapse-${itemId}]
instead of !state.collapse
Upvotes: 1