lundi 27 juin 2022

How to Handle multiple checkbox with default value checked using state with some array of object [React-JS Typescript]

i'm using multiple input checkbox for my form input in react. like image bellow:

enter image description here

this is some part of my code:

interface CheckType {
  id: any;
  desc: string;
  checked: boolean;
}

interface CheckListInputProps {
  options: Array<CheckType>;
  onChange: (e: React.ChangeEvent<HTMLInputElement>, data: Array<CheckType>) => void
}

const CheckListInput: React.FC<CheckListInputProps> = ({options, onChange}) => {
  const [initOpt, setInitOpt] = useState<Array<CheckType>([])

  useEffect(()=>{
    setInitOpt(options);
  },[options])

const changeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
  let {value, checked} = e.currentTarget
  let index = initOpt.findIndex(item => item.id===value);
  initOpt[index].checked = checked
  setInitOpt(initOpt)
  onChange(e, initOpt);
}

  return (
    <div>
      {
        initOpt.map((item, index) => (
          <div key={index}>
            <input value={item.id} checked={item.checked} onChange={changeHandler}/>
            <label>{item.desc}</label>
          </div>
       )}
    </div>)
}

when i called this function in other file:

const ChangeHandler = (e: React.ChangeEvent<HTMLInputElement>, data: Array<any>) => {
  console.log(data);
}

const options = [
  {id: 0, desc: "GET", checked: false},
  {id: 1, desc: "POST", checked: false},
  {id: 2, desc: "DELETE", checked: false}
]

return <CheckListInput options={options} onChange={ChangeHandler}/

everything works fine. the log show what i want. but the problem is in interface the checkbox won't change into checked or unchecked. how do i fix this? is it any wrong with this checked={item.checked}




Aucun commentaire:

Enregistrer un commentaire