1.5 KiB
1.5 KiB
title, tags, cover, firstSeen, lastUpdated
| title | tags | cover | firstSeen | lastUpdated |
|---|---|---|---|---|
| Collapsible content | components,children,state | washed-ashore | 2018-10-17T20:42:23+03:00 | 2021-10-13T19:29:39+02:00 |
Renders a component with collapsible content.
- Use the
useState()hook to create theisCollapsedstate variable. Give it an initial value ofcollapsed. - Use the
<button>to change the component'sisCollapsedstate and the content of the component, passed down viachildren. - Use
isCollapsedto determine the appearance of the content and apply the appropriateclassName. - Update the value of the
aria-expandedattribute based onisCollapsedto 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')
);