Created
February 27, 2024 15:38
-
-
Save pebueno/1e490c162fe9dfa1601e68eb44d53e5e to your computer and use it in GitHub Desktop.
Multiselect button React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The task is to implement multiselect from scratch (styling is not required) | |
// While closed it should show selected items separated by coma, | |
// on click it should open a list where you can check/uncheck items | |
const Component = () => { | |
const [items, setItems] = React.useState([]) | |
const [selected, setSelected] = React.useState([]) | |
const [isOpen, setIsOpen] = React.useState(false); | |
React.useEffect(() => { | |
setItems([{ label: 'd', value: 'd' }, { label: 'a', value: 'a' }, { label: 'b', value: 'b' }, { label: 'c', value: 'c' }]) | |
}, []) | |
const toggleOpen = () => { | |
setIsOpen(!isOpen); | |
} | |
const toggleItem = (value) => { | |
if (selected.includes(value)) { | |
setSelected(selected.filter((item) => item !== value)); | |
} else { | |
setSelected([...selected, value]); | |
} | |
}; | |
return ( | |
<div className="container"> | |
<input | |
id="displayInput" | |
type="text" | |
readOnly | |
value={selected.length > 0 ? selected.join(', ') : 'Select items'} | |
onClick={toggleOpen} | |
/> | |
{isOpen && ( | |
<select multiple className="dropdown" value={selected} onChange={() => {}}> | |
{items.map((item) => ( | |
<option | |
className="dropdown" | |
key={item.value} | |
value={item.value} | |
onClick={() => toggleItem(item.value)} | |
> | |
{item.label} | |
</option> | |
))} | |
</select> | |
)} | |
</div> | |
); | |
}; | |
ReactDOM.createRoot(document.getElementById('app')).render(<Component />); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.container { | |
width: 300px; | |
margin: 20px; | |
} | |
#displayInput { | |
cursor: pointer; | |
border: 1px solid #ccc; | |
padding: 5px; | |
font-size: 1.5rem | |
} | |
.dropdown { | |
font-size: 1.5rem | |
} | |
.dropdown[Multiple] { | |
display: block; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment