Home > OS >  REACT- Fill checkbox if value=1 else not filled
REACT- Fill checkbox if value=1 else not filled

Time:04-17

how can I create a checkbox that is fill when item.availability=1 (for example) elif 0 it's not filled. I can return {item.availability} in Checkbox function but I want something more generique.

export default function MenuItemDisplay() {
  ...
  const { menuId, itemId } = useParams();
  const { match } = JsonData;
  const matchData = match.find((el) => el._id_menu === menuId)?._ids ?? [];
  const item = matchData.find((el) => el._id === itemId);

  function Checkbox({ value }) {
    const [checked, setChecked] = React.useState(true);

    return (
      <label>
        <input
          type="checkbox"
          defaultChecked={checked}
          onChange={() => setChecked(!checked)}
        />
        {value}
      </label>
    );
  }
  return (
    <>
          ....
          {"Availability "}
          <Checkbox ({item[0].availability})/>
        </div>
      </div>
    </>
  );
}

Here is my code

CodePudding user response:

You can just set the received value prop as initial state of the checked state. Then make the checked prop in the input element depending on the state:

function Checkbox({ value }) {
    const [checked, setChecked] = React.useState(value);

    return (
      <label>
        <input
          type="checkbox"
          checked={checked}
          onChange={() => setChecked(checked => !checked)}
        />
        {value}
      </label>
    );
  }

Make sure to pass the prop correctly:

<Checkbox value={!!item.availability} />
  • Related