I would like to know how can I make any button changing color when selected.
Knowing that you can only selected one button at the time for each value.
Like if you click on 'White', the Black button can't have the same background color. Same for the Size, if 'L' is selected, and you click on 'S' then, 'L' take the default color and 'S' the background color when an element is selected.
Thanks in advance to anyone who tries to help me!
I've tried to use If Statement but I'm not sure I'm doing it right.
{values.map((value) => {
const id = `option-${name}-${value}`;
const checked = setSelectedOption[name] === value;
const [bgSelected, setBgSelected] = useState(false);
const handleClick = () => {
setBgSelected(!bgSelected);
}
const handleSelected = () => {
setSelectedOption(name, value);
if (bgSelected === true) {
setBgSelected(false);
handleClick()
} else {
setBgSelected(true);
handleClick()
}
}
return (
<div key={id} className="product-option-value text-left">
<div
type="button"
checked={checked}
name={name}
value={value}
id={id}
// onChange={() =>setSelectedOption(name, value)}
className=""
/>
<label
htmlFor={id}
//onClick={handleClick}
className={bgSelected ? "bg-blue-800" : "bg-blue-200"}
onClick={handleSelected}
>{value}</label>
</div>
)
})}
</div>
It seems like you are calling the wrong property from
useProductOptions
to determine if your product has been selected, you are usingsetSelectedOption[name]
instead of theselectedOptions[name]
.Based on this one value (
selectedOptions[name]
) you can also determine if a value has been selected so you do not need to create an extra state for the background.Try and use:
=== old answer before the post update ===
I am not sure why your code is not throwing errors, but you should (and can) not use a
useState
inside of amap
.You could write this component using just one state, as below.
A working example can be found at this codesandbox