We use the React.useState() hook to create the "isCollapsed" state variable with an initial value of props.collapsed.
We use an object, status, to hold the styles for individual components and their states.
We use a <div> to wrap both the <button> that alters the component's "isCollapsed" state and the content of the component.
We passed it down via props.children. We display the content, based on "isCollapsed" and apply the appropriate CSS rules from the status object.
We update the value of the aria-expanded attribute based on "isCollapsed" to make the component accessible.
const Collapse = (props) => {
const [isCollapsed, setIsCollapsed] = React.useState(props.collapsed);
const status = {
collapsed: {
display: "none"
},
expanded: {
display: "block"
},
buttonStyle: {
display: "block",
width: "100%"
}
};
return (
<div>
<button
style={status.buttonStyle}
onClick={() => setIsCollapsed(!isCollapsed)}
>
{isCollapsed ? "Show" : "Hide"} content
</button>
<div
className="collapse-content"
style={isCollapsed ? status.collapsed : status.expanded}
aria-expanded={isCollapsed}
>
{props.children}
</div>
</div>
);
}
ReactDOM.render(
<Collapse>
<h1>This is a Collapse ReactJS Component</h1>
<p>criscond.co.uk</p>
</Collapse>,
document.getElementById('root')
);