Toggle Multiple Filters
ReactJS
Medium
6 views
Problem Description
Make three filter chips (Easy, Medium, Hard) that can be toggled.
Output Format
Render a React component.
Constraints
Store selected filters in an array and toggle by value.
Official Solution
import React, { useState } from 'react';
const levels = ['Easy', 'Medium', 'Hard'];
function Chip({ active, children, onClick }) {
return (
<button
type='button'
onClick={onClick}
style={{ padding: '8px 12px', borderRadius: 999, border: '1px solid ' + (active ? '#0b5' : '#ddd'), background: active ? '#eafaf1' : '#fff', color: '#124', fontWeight: 600 }}
>
{children}
</button>
);
}
export default function App() {
const [selected, setSelected] = useState(['Easy']);
function toggle(level) {
setSelected((prev) => (prev.includes(level) ? prev.filter((x) => x !== level) : [...prev, level]));
}
return (
<div style={{ padding: 16 }}>
<strong>meetcode filters</strong>
<div style={{ display: 'flex', gap: 10, marginTop: 10 }}>
{levels.map((l) => (
<Chip key={l} active={selected.includes(l)} onClick={() => toggle(l)}>
{l}
</Chip>
))}
</div>
<p style={{ marginTop: 12, color: '#555' }}>Selected: {selected.length ? selected.join(', ') : 'None'}</p>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!