Home > front end >  Setting `checked` property of Checkbox Toggle Component
Setting `checked` property of Checkbox Toggle Component

Time:10-07

I'm working on a checkbox component who's styling depends on the checked status of the checkbox. This works fine when the user clicks the checkbox, but if it's set manually, that property gets overridden.

component:

import React, {useState} from "react";

export default function IconCheck({children}) {

const [isChecked, setIsChecked] = useState(false);

return(
  <span className="btn-group-toggle" data-toggle="buttons">
    <label className={`btn ${checkSize} ${isChecked ? "btn-primary" : "btn-outline-primary"}`}>
      <input
        type="checkbox"
        onChange={() => setIsChecked((prev) => !prev)}
        checked={isChecked}
      />
      {children}
    </label>
  </span>
)
}

story:

<IconCheck>Default</IconCheck>
<IconCheck isChecked>Should be Checked</IconCheck>

I believe this has to do with the useState, but I'm not sure what change is needed. Any tips?

CodePudding user response:

I think you might be confusing props with state. You probably want your component to begin with a default value, and than control this value using useState, so here is one way to do it by accepting defaultValue prop for the component:

import React, {useState} from "react";

export default function IconCheck({ children, defaultValue }) {
  const [isChecked, setIsChecked] = useState(defaultValue);

  return(
    <span className="btn-group-toggle" data-toggle="buttons">
        <label>
          <input
            type="checkbox"
            onChange={() => setIsChecked((prev) => !prev)}
            checked={isChecked}
          />
          {children}
        </label>
    </span>
  )
}

Then in the parent component you call

<IconCheck defaultValue={true}>Should be checked</IconCheck>

CodePudding user response:

  • get prop isCheckedProp
  • useState( isCheckedProp|| false ,); or more proffesional using useEffect
  • Related