trainReact.com
||

9. Implement a Collapsible Section Component

Easy
Category: Component Patterns
useStateConditional RenderingReusable ComponentsChildren Prop

Problem Description

Create a reusable CollapsibleSection component in React that allows users to toggle the visibility of its content. This component should have a header that remains visible at all times and a content area that can be shown or hidden.

Your task is to implement the toggle button logic and functionality to show or hide the content when clicked.

Requirements

  1. The content (passed as children) should be hidden by default(not present in the DOM).

  2. Clicking the toggle button should show or hide the content.

  3. The toggle button should have appropriate text to indicate the current state ("Show" / "Hide").

CollapsibleSection usage examples

1<CollapsibleSection title="Section 1">
2  <p>This is the content of section 1.</p>
3</CollapsibleSection>
4
5<CollapsibleSection title="Section 2">
6  <ul>
7    <li>Item 1</li>
8    <li>Item 2</li>
9    <li>Item 3</li>
10  </ul>
11</CollapsibleSection>
12
import React from 'react';
import './CollapsibleSection.css';

const CollapsibleSection = ({ title = 'Collapsible Section', children }) => {
  const isExpanded = false;

  const toggleExpand = () => null;

  return (
    <div className="collapsible-section" data-testid="collapsible-section">
      <div className="collapsible-header" data-testid="collapsible-header">
        <h3 data-testid='collapsible-title'>{title}</h3>
        <button
          data-testid="collapsible-toggle"
          aria-controls="collapsible-content"
          aria-expanded={isExpanded}
        >
          {true ? 'Hide' : 'Show'}
        </button>
      </div>
      <div
        id="collapsible-content"
        data-testid="collapsible-content"
        aria-hidden={!isExpanded}
        className="collapsible-content"
      >
        {isExpanded && (
          children || <p>No content available</p>
        )}
      </div>
    </div>
  );
};

export default CollapsibleSection;

Open browser consoleTests