You see here, the first radio button defaultChecked={index === 0}
is by default checked. I am storing the mapped variant
object when it’s changed.onChange
. how do I store the value of variant
when user doesn’t change anything and just press add item?
I can’t set the state inside .map
it causes render issues.
JavaScript
x
21
21
1
const [variantOption, setVariantOption] = useState({});
2
const [variant, setVariant] = useState([]);
3
props.selectedCustomItem.variants.map((variant, index) => {
4
{variant.options.map((option, index) => {
5
<input
6
type="radio"
7
name="variant-select"
8
id="variant-select"
9
defaultChecked={index === 0}
10
value={option.price}
11
onChange={(e) => {
12
setVariantOption(option);
13
setVariant(variant);
14
}}
15
/>}
16
<button
17
onClick={() => {
18
props.addFoodItems(variant, variantOption);
19
}}
20
>add item</button>
21
Advertisement
Answer
If you are using checkbox and the first is by default selected, then you can initialise your state with the first value present in the state like useState(props.selectedCustomItem.variants[0])
JavaScript
1
28
28
1
const [variantOption, setVariantOption] = useState();
2
const [variant, setVariant] = useState(props.selectedCustomItem.variants[0]);
3
4
useEffect(() => {
5
if (variantOption == null && variant && variant.length > 0) {
6
setVariantOption(variant.options[0]);
7
}
8
}, [variantOptions, variant]);
9
10
props.selectedCustomItem.variants.map((variant, index) => {
11
{variant.options.map((option, index) => {
12
<input
13
type="radio"
14
name="variant-select"
15
id="variant-select"
16
defaultChecked={index === 0}
17
value={option.price}
18
onChange={(e) => {
19
setVariantOption(option);
20
setVariant(variant);
21
}}
22
/>}
23
<button
24
onClick={() => {
25
props.addFoodItems(variant, variantOption);
26
}}
27
>add item</button>
28
Also, I assume that props.selectedCustomItem.variants
is not null or undefined.