Skip to content
Advertisement

How to set the state when radio button is by default checked?

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.

const [variantOption, setVariantOption] = useState({});
const [variant, setVariant] = useState([]);
props.selectedCustomItem.variants.map((variant, index) => {
{variant.options.map((option, index) => {
<input
type="radio"
name="variant-select"
id="variant-select"
defaultChecked={index === 0}
value={option.price}
onChange={(e) => {
setVariantOption(option);
setVariant(variant);
}}
/>}
<button
  onClick={() => {
    props.addFoodItems(variant, variantOption);
  }}
>add item</button> 

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])

const [variantOption, setVariantOption] = useState();
const [variant, setVariant] = useState(props.selectedCustomItem.variants[0]);

useEffect(() => {
  if (variantOption == null && variant && variant.length > 0) {
    setVariantOption(variant.options[0]);
  }
}, [variantOptions, variant]);

props.selectedCustomItem.variants.map((variant, index) => {
{variant.options.map((option, index) => {
<input
type="radio"
name="variant-select"
id="variant-select"
defaultChecked={index === 0}
value={option.price}
onChange={(e) => {
setVariantOption(option);
setVariant(variant);
}}
/>}
<button
  onClick={() => {
    props.addFoodItems(variant, variantOption);
  }}
>add item</button> 

Also, I assume that props.selectedCustomItem.variants is not null or undefined.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement