0

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.

1 Answer 1

1

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;

Sign up to request clarification or add additional context in comments.

4 Comments

with {name} the page wont crash. When I replace props.filteredTags with values, the website wont load: "FilterCheckboxBar.tsx:27 Uncaught TypeError: values.map is not a function"
@Spluli Oh, yes, values is an Object. I've edited my answer to address that.
now it's working! but the checkmarks didn't dissapear. With removing checked={values} it's working now . thx <3
@Spluli You can use checked={values[list]}

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.