Reputation: 109
So I have this data:
const data = [
{
id: 1,
category: "category1",
name: "N/A",
price: 0,
},
{
id: 2,
category: "category1",
name: "Cheese",
price: 220,
},
{
id: 3,
category: "category2",
name: "Eggs",
price: 420,
},
{
id: 4,
category: "category2",
name: "Bananas",
price: 515,
}
which gets fed into my 'RadiosBlock' component via the 'items' prop:
<form>
<RadiosBlock
items={data}
category="category1"
onSelectHandler={selectionHandler}
>
</RadiosBlock>
<RadiosBlock
items={data}
category="category2"
onSelectHandler={selectionHandler}
>
</RadiosBlock>
<h2>Your order:</h2>
Total: £
{selections.price}
</form>
and then filtered via the 'category' prop:
const categoryFilter = props.items.filter(
(c) => c.category === props.category
);
<ul className="items-block__inner">
{categoryFilter.map((item) => {
return (
<RadioItem
isChecked={selectedItem.id === item.id}
key={item.id}
itemName={item.name}
itemPrice={item.price}
onClick={() => clickHandler(item)}
/>
);
})}
</ul>
My 'RadioItem' is a clickable list element that has been styled to look like a radio button.
What I'd like to do is show the total price of the elements that have been selected (only one can be selected per category, same as how radio buttons work). I guess I need to add the selected items to an array which is in state, but how would I ensure that only one per category is in the array at any one time?
I hope this makes sense, any help greatly appreciated. If you require more information let me know.
Upvotes: 0
Views: 47
Reputation: 693
A good way to avoid repetitions would be to use a map.
const [selectedItems, setSelectedItems] = useState({});
const selectionHandler = (item) => {
setSelectedItems((prev) => ({ ...prev, [item.category]: item}));
}
In case you need an array when sending an async request or for some other logic, just use Object.values
const onSubmit (values) => {
const categoryItems = Object.values(selectedItems);
// Send XHR Request
}
Keep in mind this answer will not be valid if you have two radio groups for the same category. They will be overriden.
Upvotes: 1