I want to make the button active when the checkbox is active. I did this for one checkbox, but how can I do it with 2 checkboxes? Button should not be enabled if even one of the checkboxes is not checked
This is how the button activity I do with a single checkbox:
import {useState} from "React";
export default function App() {
const [change, setChange] = useState(true);
const buttonHandler = () => {
setChange(!change)
}
return (
<>
<button disabled={change}>button</button>
<input type="checkbox" onChange={buttonHandler}/>
<input type="checkbox" onChange={buttonHandler}/>
<>
);
}
You need to hold the state of both checkboxes to make sure they are both checked before enabling the button:
import {useState} from "React";
export default function App() {
const [checkbox1, setCheckbox1] = useState(false);
const [checkbox2, setCheckbox2] = useState(false);
const button1Handler = () => {
setCheckbox1(current => !current);
}
const button2Handler = () => {
setCheckbox2(current => !current);
}
return (
<>
<button disabled={!checkbox1 || !checkbox2}>button</button>
<input type="checkbox" checked={checkbox1} onChange={button1Handler}/>
<input type="checkbox" checked={checkbox2} onChange={button2Handler}/>
<>
);
}
What you want is a state that holds an array of values, each of a checkbox. I would prefer an array so you only have one button handler, and adding more checkboxes should be easy.
import {useState} from "React";
export default function App() {
const [change, setChange] = useState([true, true]);
const buttonHandler = (index) => {
const newState = [...change];
newState[index] = !newState[index]
setChange(newState)
}
return (
<>
<button disabled={!change[0] && !change[1]}>button</button>
<input type="checkbox" value={change[0]} onChange={()=>buttonHandler(0)}/>
<input type="checkbox" value={change[1]} onChange={()=>buttonHandler(1)}/>
<>
);
}