I have an Checkbox input in React Bootstrap.
if my Variable isTrue=true
I want to set checked to my input.
I'm adding checked ={isTrue ? true : false}
to the input, but after I do this, I'm unable to uncheck it. (I have this input in a loop)
<input type='checkbox' checked ={isTrue ? true : false} />
When I do this:
<input type="checkbox" {checked ? 'checked' : ''} name="example" />
I get error: "Spread types may only be created from object types.ts(2698)"
How can I conditionally set checked
to a checkbox input?
CodePudding user response:
You will need to useEffect
that will run when isTrue
changes (from false to true). So it will change the value of the state variable that is bind to a checkbox:
const { useEffect, useState } = React;
function App() {
const [isTrue, setIsTrue] = useState(false);
const [checkBoxValue, setCheckBoxValue] = useState(false);
const onButtonClick = () => {
setIsTrue((curr) => !curr);
};
useEffect(() => {
if (!isTrue) return;
setCheckBoxValue(true);
}, [isTrue]);
return (
<div className="App">
<p>IsTrue: {isTrue.toString()}</p>
<p>CheckBox value: {checkBoxValue.toString()}</p>
<button type="button" onClick={onButtonClick}>
Toggle isTrue
</button>
<input
type="checkbox"
onChange={() => setCheckBoxValue((curr) => !curr)}
checked={checkBoxValue}
/>
</div>
);
}
ReactDOM.createRoot(
document.getElementById("root")
).render(
<App />
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
<div id="root"></div>
CodePudding user response:
I added this and it worked.
<input type="checkbox" name="example" {...(isTrue && { checked: true })} />
CodePudding user response:
You can
<input type='checkbox' checked ={isTrue} onClick={handleChange} />
And create your function that handles the onClick and change the isTrue accordingly