Although I've come across similar questions, none of them have addressed mine directly.
I managed to create a collapsible div component that expands itself upon click. However, I am looking for a way to make it so that when one div is expanded, all other expanded components will collapse.
The parent component where the collapsible component is included:
import React from 'react';
import { Collapsible } from '../../components';
const Parent = () => {
return (
<div>
<Collapsible label="First label">
<p>Children</p>
</Collapsible>
<Collapsible label="Second label">
<p>Children</p>
</Collapsible>
<Collapsible label="Third label">
<p>Children</p>
</Collapsible>
</div>
);
};
export default Parent;
The Collapsible component:
import React, { Component } from 'react';
class Collapsible extends Component {
constructor(props) {
super(props);
this.state = {
opened: false,
};
this.openCollapsible = this.openCollapsible.bind(this);
}
openCollapsible() {
this.setState(prevState => ({
opened: !prevState.opened,
}));
}
render() {
const { label, children } = this.props;
const { opened } = this.state;
return (
<div>
<h2 onClick={this.openCollapsible}>
{label}
</h2>
{opened ? <div>{children}</div> : null}
</div>
);
}
}
export default Collapsible;
Overall, everything seems to be working fine. I just need help figuring out how to collapse all other collapsible components when one is expanded. Any assistance or guidance would be highly appreciated, even if it's just pointing me in the right direction for further research.
Sandbox: https://codesandbox.io/s/collapsible-component-tnhtn
Best regards!