Toggle Section Component
ReactJS
Hard
6 views
Problem Description
Build a collapsible section using details/summary style but with React state.
Output Format
Render a React component.
Constraints
Animate is optional. Keep logic simple.
Official Solution
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>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!