0

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 ?

2 Answers 2

1

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}/>
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.