Renders a component with collapsible content.
useState()
hook to create the isCollapsed
state variable. Give it an initial value of collapsed
.<button>
to change the component's isCollapsed
state and the content of the component, passed down via children
.isCollapsed
to determine the appearance of the content and apply the appropriate className
.aria-expanded
attribute based on isCollapsed
to make the component accessible..collapse-button {
display: block;
width: 100%;
}
.collapse-content.collapsed {
display: none;
}
.collapsed-content.expanded {
display: block;
}
const Collapse = ({ collapsed, children }) => {
const [isCollapsed, setIsCollapsed] = React.useState(collapsed);
return (
<>
<button
className="collapse-button"
onClick={() => setIsCollapsed(!isCollapsed)}
>
{isCollapsed ? 'Show' : 'Hide'} content
</button>
<div
className={`collapse-content ${isCollapsed ? 'collapsed' : 'expanded'}`}
aria-expanded={isCollapsed}
>
{children}
</div>
</>
);
};
ReactDOM.render(
<Collapse>
<h1>This is a collapse</h1>
<p>Hello world!</p>
</Collapse>,
document.getElementById('root')
);
Would you like to help us improve 30 seconds of code?Take a quick survey
React, Components
Renders an accordion menu with multiple collapsible content elements.
React, Components
Renders a tree view of a JSON object or array with collapsible content.
React, Components
Renders a tabbed menu and view component.