Reputation: 381
What's the best way to create a checkbox that gets a default status but can still be modified.
<div className="master">
<input className="tgl tgl-skewed" id={id} type="checkbox" onChange={onChange} name={flag} checked={lock}/>
<label className="slave tgl-btn" data-tg-off={flag + " is OFF"} data-tg-on={flag + " is ON"} htmlFor={id}></label>
</div>
In this example above I get a default status (lock) that can be "true" or "false" this changes the checkbox from "checked" to "unchecked". Unfortunately this also makes it impossible to change this status by clicking on the relevant checkbox.
Any ideas ?
Upvotes: 0
Views: 501
Reputation: 8751
You can use defaultChecked
props for the input tag in react.
<input className="tgl tgl-skewed" id={id} type="checkbox" onChange={onChange} name={flag} defaultChecked={lock}/>
Upvotes: 1
Reputation: 370639
Put the lock
into state, and have the change handler toggle the boolean:
const App = ({ lock }) => {
const [checked, setChecked] = React.useState(lock);
const onChange = () => setChecked(!checked);
const id = 'foo';
return (
<div className="master">
<input className="tgl tgl-skewed" id={id} type="checkbox" onChange={onChange} checked={checked}/>
<label className="slave tgl-btn" htmlFor={id}></label>
</div>
);
};
ReactDOM.render(<App lock={true} />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class="react"></div>
Upvotes: 1