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.
const List = ({ items }) => {
const [cart, setCart] = useState([]);
const updateCart = ({ item }) =>
cart.includes(item.name)
? setCart([
/* If the item is already selected, remove it from the top list.*/
...cart.filter((selectedItem) => selectedItem !== item.name),
(item.isActive = false),
])
/* Else add it to the list */
: setCart([...cart, item.name, (item.isActive = true)]);
return (
<Fragment>
<ul className="Selected">
{cart.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
<ul className="List">
{items.map((item) => (
<li
key={item.name}
className={`List__item List__item--${item.color}`}
>
<button
className={`list__item__cta ${item.isActive ? "is-active" : ""}`}
onClick={() => updateCart({ item })}
>
{item.name}
</button>
</li>
))}
</ul>
</Fragment>
);
};
// ---------------------------------------
// Do NOT change anything below this line.
// ---------------------------------------
const sizes = ['tiny', 'small', 'medium', 'large', 'huge'];
const colors = ['navy', 'blue', 'aqua', 'teal', 'olive', 'green', 'lime', 'yellow', 'orange', 'red', 'maroon', 'fuchsia', 'purple', 'silver', 'gray', 'black'];
const fruits = ['apple', 'banana', 'watermelon', 'orange', 'peach',...
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.