Tabs With Local State
ReactJS
Medium
6 views
Problem Description
Build basic tabs with buttons and show the active panel.
Output Format
Render a React component.
Constraints
Keep active tab in state and render only active content.
Official Solution
import React, { useState } from 'react';
const tabs = [
{ id: 'topics', label: 'Topics', content: 'Pick a topic on meetcode.' },
{ id: 'practice', label: 'Practice', content: 'Solve one small question.' },
{ id: 'notes', label: 'Notes', content: 'Read a quick explanation.' }
];
export default function App() {
const [active, setActive] = useState('topics');
const current = tabs.find((t) => t.id === active);
return (
<div style={{ padding: 16, width: 420 }}>
<div style={{ display: 'flex', gap: 10 }}>
{tabs.map((t) => (
<button
key={t.id}
type='button'
onClick={() => setActive(t.id)}
style={{ padding: '8px 12px', borderRadius: 12, border: '1px solid #ddd', background: t.id === active ? '#0b5' : '#fff', color: t.id === active ? '#fff' : '#124' }}
>
{t.label}
</button>
))}
</div>
<div style={{ marginTop: 12, border: '1px solid #eee', borderRadius: 14, padding: 12 }}>
<strong>{current.label}</strong>
<p style={{ margin: '8px 0 0 0', color: '#555' }}>{current.content}</p>
</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!