Create Collapsible React Components

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to create a collapsible content component in React using the useState hook. This component will allow users to toggle the visibility of content by clicking on a button, making it a useful tool for organizing and presenting information on a webpage. By the end of this lab, you will have a better understanding of how to create reusable components in React that improve the accessibility and user experience of your web applications.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/FundamentalsGroup -.-> react/conditional_render("`Conditional Rendering`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38344{{"`Create Collapsible React Components`"}} react/event_handling -.-> lab-38344{{"`Create Collapsible React Components`"}} react/conditional_render -.-> lab-38344{{"`Create Collapsible React Components`"}} react/hooks -.-> lab-38344{{"`Create Collapsible React Components`"}} react/use_state_reducer -.-> lab-38344{{"`Create Collapsible React Components`"}} end

Collapsible Content

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

This function renders a collapsible component with a button that toggles the visibility of its content. Here's how to use it:

  1. Use the useState() hook to create the isCollapsed state variable, which represents whether the content is currently collapsed or expanded. Initialize it to collapsed.
  2. Use the <button> element to toggle the isCollapsed state and show/hide the content passed down via the children prop.
  3. Use isCollapsed to apply the appropriate CSS class to the content container, either collapsed or expanded, which determines its appearance.
  4. Update the aria-expanded attribute of the content container based on the isCollapsed state, to make the component accessible to users with disabilities.

Here's the CSS code needed for this component:

.collapse-button {
  display: block;
  width: 100%;
}

.collapse-content.collapsed {
  display: none;
}

.collapse-content.expanded {
  display: block;
}

And here's the JavaScript code:

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>
    </>
  );
};

To use this component, simply call it with the content you want to collapse:

ReactDOM.createRoot(document.getElementById("root")).render(
  <Collapse>
    <h1>This is a collapse</h1>
    <p>Hello world!</p>
  </Collapse>
);

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Collapsible Content lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like