React, Components, Children, State

Renders a component with collapsible content.

  • Use the useState() hook to create the isCollapsed state variable with an initial value of collapsed.
  • Use the <button> to change the component's isCollapsed state and the content of the component, passed down via children.
  • Determine the appearance of the content, based on isCollapsed and apply the appropriate className.
  • Update the value of the 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 (
        onClick={() => setIsCollapsed(!isCollapsed)}
        {isCollapsed ? 'Show' : 'Hide'} content
        className={`collapse-content ${isCollapsed ? 'collapsed' : 'expanded'}`}
    <h1>This is a collapse</h1>
    <p>Hello world!</p>
View on GitHub

Recommended snippets

  • Accordion

    React, Components

    Renders an accordion menu with multiple collapsible content elements.

  • TreeView

    React, Components

    Renders a tree view of a JSON object or array with collapsible content.

  • Tabs

    React, Components

    Renders a tabbed menu and view component.