0

I tried to create an array in each click using ReactJS and Typescript. Here's my code:

const FormTags: React.FC = () => {
     const [selected, setSelected] = React.useState<[]>([])

     const handleTag = (e: React.FormEvent<HTMLInputElement>) => {
             let id: number = +e.currentTarget.value
             //working, show me each id
             console.log(id)
             // not working
             setSelected([...id]) // error here
             // Argument of type 'number' is not assignable to parameter of type 
             // 'SetStateAction<[]>'.
     }

     //retrieve tags working well, show me all list tags
     return (
        <form>
            {tags && tags.map(tag: any) => (
                <label key={tag.id}>
                    <input type="checkbox" value={tag.id} onClick={handleTag}/>
                </label>
            )}
       </form>
    )
}

I want to build an array like this [1, 2, 3, ...] in each click get ID of the tags and persist it with setSelected. How can I do it?

1
  • 1
    useState<number[]>([]) Commented Jun 9, 2020 at 1:30

1 Answer 1

1

I think that's what you want:

const FormTags: React.FC = () => {
  const [selected, setSelected] = React.useState<number[]>([]);

  const handleTag = (e: React.FormEvent<HTMLInputElement>) => {
    const id: number = +e.currentTarget.value;
    const { checked } = e.currentTarget;

    if (checked) {
      setSelected(prev => [...prev, id]);
    } else {
      setSelected(prev => prev.filter(item => item !== id));
    }
  };

  return (
    <form>
      {tags &&
        tags.map((tag: any) => (
          <input
            checked={selected.includes(tag.id)}
            type="checkbox"
            value={tag.id}
            onClick={handleTag}
          />
        ))}
    </form>
  );
};

When you check the checkbox, its id will be added to the select state. If you uncheck, the id will be removed.

The problem in your code was that you were trying to destruct the id, which is a number, when actually you must destruct the previous array and then add the id. This can be easily done passing to setSelect a function that will receive the previous state and return the new state.

setSelected(prev => [...prev, id]);

Check the React documentation for more info.

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

Comments

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.