Toggle Section Component

Toggle Section Component

Hard ReactJS Component Design 32 views
Explanation Complexity

Problem Statement

Build a collapsible section using details/summary style but with React state.

Input Format

No input.

Output Format

Render a React component.

Constraints

Animate is optional. Keep logic simple.

Input / Output Format

Input Format
No input.
Output Format
Render a React component.
Constraints
Animate is optional. Keep logic simple.

Examples

Input:
Output:
(React code)

Example Solution (Public)

ReactJS
import React, { useState } from 'react';

function Collapsible({ title, children }) {
  const [open, setOpen] = useState(false);

  return (
    <section style={{ border: '1px solid #eee', borderRadius: 14, padding: 12, width: 420 }}>
      <button type='button' onClick={() => setOpen((v) => !v)} style={{ width: '100%', textAlign: 'left', border: 0, background: 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <strong>{title}</strong>
        <span aria-hidden='true'>{open ? '−' : '+'}</span>
      </button>
      {open ? <div style={{ marginTop: 10 }}>{children}</div> : null}
    </section>
  );
}

export default function App() {
  return (
    <Collapsible title='What is meetcode?'>
      <p style={{ margin: 0 }}>A place to practice small coding questions.</p>
    </Collapsible>
  );
}

Official Solution Code

import React, { useState } from 'react';

function Collapsible({ title, children }) {
  const [open, setOpen] = useState(false);

  return (
    <section style={{ border: '1px solid #eee', borderRadius: 14, padding: 12, width: 420 }}>
      <button type='button' onClick={() => setOpen((v) => !v)} style={{ width: '100%', textAlign: 'left', border: 0, background: 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <strong>{title}</strong>
        <span aria-hidden='true'>{open ? '−' : '+'}</span>
      </button>
      {open ? <div style={{ marginTop: 10 }}>{children}</div> : null}
    </section>
  );
}

export default function App() {
  return (
    <Collapsible title='What is meetcode?'>
      <p style={{ margin: 0 }}>A place to practice small coding questions.</p>
    </Collapsible>
  );
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.