I have two components namely, ‘SectionFruits’ & ‘ToggleFruit’ and a state called ‘selectedFruits’ which is an array of objects like so:
useState([
{
name: 'Apple',
price: '',
quantity: '',
},
{
name: 'Mango',
price: '',
quantity: '',
},
])
‘ToggleFruit’ is a component which has the logic of add/remove fruit’s properties (name, price, quantity) like so:
import React, { useState, createRef } from "react";
import styled from "styled-components";
const StyledToggleFruit = styled.div`
margin-bottom: 12px;
& > div {
display: flex;
align-items: center;
input[type="checkbox"] {
margin: 0;
}
h6 {
margin: 0;
cursor: pointer;
color: coral;
}
}
aside {
display: flex;
margin-top: 2px;
input {
margin-right: 8px;
}
}
`;
const ToggleFruit = ({
Id,
state,
setState,
ischecked,
label,
price,
quantity
}) => {
const toggleRef = createRef();
const [priceValue, setPriceValue] = useState(price);
const [quantityValue, setQuantityValue] = useState(quantity);
const [checkedState, setCheckedState] = useState(
ischecked ? ischecked : false
);
const handleToggle = (e) => {
setCheckedState(!checkedState);
if (state.some((object) => object.name.includes(label))) {
const removeFruitArr = state.filter((item) => item["name"] !== label);
setState(removeFruitArr);
} else {
setState((prevState) => [
...prevState,
{
name: label,
price: priceValue,
quantity: quantityValue
}
]);
}
};
return (
<StyledToggleFruit>
<div onClick={handleToggle}>
<div>
<input
ref={toggleRef}
onChange={handleToggle}
ischecked={ischecked && ischecked.toString()}
checked={checkedState}
type="checkbox"
/>
</div>
<h6>{label}</h6>
</div>
{checkedState && (
<aside>
<input
required
onChange={(e) => setPriceValue(e.target.value)}
value={priceValue}
type="text"
placeholder="Price"
/>
<input
required
onChange={(e) => setQuantityValue(e.target.value)}
value={quantityValue}
type="text"
placeholder="Quantity"
/>
</aside>
)}
</StyledToggleFruit>
);
};
export default ToggleFruit;
And ‘SectionFruits’ simply runs a map over FRUITS and renders them in the DOM. There are two issues I’m facing:
- The toggle(add/remove) of fruits in the state is behaving weirdly
- Price & Quantity are not being added to the state
Sandbox link: https://codesandbox.io/s/festive-haze-5ono9
>Solution :
I’ve edited a bit your code on codesandbox, please check it out:
https://codesandbox.io/s/upbeat-estrela-5yqbs?file=/src/components/ToggleFruit.js:660-676