const { Fragment, useState } = React;
// Implement a feature to allow item selection with the following requirements:
// 1. Clicking an item selects/unselects it.
// 2. Multiple items can be selected at a time.
// 3. Make sure to avoid unnecessary re-renders of each list item in the big list (performance).
// 4. Currently selected items should be visually highlighted.
// 5. Currently selected items' names should be shown at the top of the page.
//
// Feel free to change the component structure at will.
// utility function to check if a name is selected
const isSelected = (selected, name) => Boolean(selected[name]);
// utility function to get the list of selected names
const getSelected = (selected) => {
const keys = Object.keys(selected);
return keys.filter((name) => isSelected(selected, name));
}
const List = ({ items }) => {
const [selected, setSelected] = useState({});
return (
<Fragment>
<div className="Selected">
<label
className="Selected__label"
for="selected"
>Selected Items</label>
<output name="selected" id="selected">{getSelected(selected).join(", ")}</output>
</div>
<ul className="List">
{items.map(({name, color}) => (
<Item
key={name}
name={name}
color={color}
selected={isSelected(selected, name)}
onClick={() => setSelected((selected) => ({
...selected,
[name]: !isSelected(selected, name)
}))}
/>
))}
</ul>
</Fragment>
);
};
const Item = ({ name, color, selected, onClick}) => (
<li
className={`
List__item
List__item--${color}
${selected ? "List__item--selected" : ""}
`}
onClick={() => onClick()}
>
{name}
</li>
);
// ---------------------------------------
// Do NOT change anything below this line.
// ---------------------------------------
const sizes = ['tiny', 'small', 'medium', 'large',...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.