Create a React collapsible box component

In this snippet, we learn how to create a collapsible box component in React

First step: Create a component call Collapsible.js with JSX code below

import React from "react";

function onCollapsible(e) {
  e.persist();
  e.target.classList.toggle("active");
  const content = e.target.nextElementSibling;
  if (content.style.maxHeight) {
    content.style.maxHeight = null;
  } else {
    content.style.maxHeight = content.scrollHeight + "px";
  }
}

function Collapsible({ items }) {
  return items.map((item, index) => (
    <div key={index} className="collapsible">
      <button className="collapsible-header" onClick={e => onCollapsible(e)}>
        {item.title}
      </button>
      <div className="collapsible-content">
        <p>{item.content}</p>
      </div>
    </div>
  ));
}

export default Collapsible;

Copy this code


Step 2: Import Collapsible and fill the data to your app

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";
import Collapsible from "./Collapsible";

const colaps = [
  {
    title: "The standard Lorem Ipsum passage, used since the 1500s",
    content:
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut "
  },
  {
    title:
      'Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC',
    content:
      "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium"
  },
  {
    title: "1914 translation by H. Rackham",
    content:
      "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will "
  }
];

function App() {
  return (
    <div className="App">
      <Collapsible items={colaps} />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Copy this code


In the code above, colaps array contain all of collapsible items, if you want a single collapsible box, you just put one item in this array.

Step 3: Add CSS code below to your style file

.collapsible-header {
  background-color: rgb(8, 150, 206);
  color: white;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
  border-bottom: 1px solid #fff;
}
.active,
.collapsible-header:hover {
  background-color: rgb(14, 93, 158);
}
.collapsible-header:after {
  content: "\002B";
  color: white;
  font-weight: bold;
  float: right;
  margin-left: 5px;
}
.active:after {
  content: "\2212";
}
.collapsible-content {
  padding: 0 18px;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
  background-color: #f1f1f1;
}
Copy this code


Click on title bar to see the result in the demo below: