Home > database >  how to do a checklist with a variable array?
how to do a checklist with a variable array?

Time:11-21

I want to build a self updating filter with checkboxes:

//extract tags to new array
const tags = [...new Set(shooting.map(({ tag }) => tag).flat(1))];
//  result: tags = ['wedding', 'couple', 'NSWF']  // <- here undefinded count of tags !

function Test() {
  return (
      <FilterCheckboxBar
       filteredTags={tags} />
  );}
export default Test;

FilterCheckboxBar:



interface Filter {
  filteredTags: any;
}

function FilterCheckboxBar(props: Filter) {


  const [values, setValues] = useState<any>([]);   // <- I guess here is something missing

  //  ----- Handle Checkbox-----                   // <- or in this one is an error
  const handleChange = (e: any) => {
    setValues((prevState: any) => {
      const [name] = e.target;
      return {
        ...prevState,
        [name]: !prevState[name],
      };
    });
  };

  return (
    <div className="filterbar">

  {/* this list my checkboxes  */}
      {props.filteredTags.map((list: any, i: any) => (
        <label key={i} htmlFor={list}>
          <input
            className="checkbox"
            type="checkbox"
            name={list}
            id={list}
            onChange={(e) =>handleChange(e)}
            checked={values}
          />
          {list}
        </label>
      ))}
    </div>
  );
}

export default FilterCheckboxBar;

by clicking on one checkbox, my page gets white and in the console this massage comes: Uncaught TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))

I guess I have to do something with useState but do not know,how to build this.

CodePudding user response:

You can do something like this:

function FilterCheckboxBar(props: Filter) {
  const [values, setValues] = useState<any>(props.filteredTags.reduce((a, c) => (a[c] = false, a), {}));

  ..

  return (
    <div className="filterbar">
      {Object.keys(values).map((list: any, i: any) => (
        ..
      ))}
    </div>
  );
}

export default FilterCheckboxBar;

Also, instead of const [name] = e.target; it should be const { name } = e.target;

  • Related