1

I am not able to handle multiple selection, due to the fact that I use State and everytime I select an option, a new item is added, but I need to store all the results in an array.

Please find bellow my code:

const [categories, setCategories] = useState([]);

return (
    <div className="create">
      <h2>Add a New Rating</h2>
      <form onSubmit={handleSubmit}>
        <label>Review title:</label>
        <label>Rating:</label>
       

        <select
          style={{ height: "170px" }}
          className="multiple"
          multiple={true}
          value={categories}
          onChange={(e) => setCategories(e.target.value)} #<-- here, I don't know how to store more items in the initial array
        >
          {data.categories.data.map((category) => (
            <option value={category.id} key={category.id}>
              {category.attributes.name}
            </option>
          ))}
        </select>

        <button>Add Review</button>
      </form>
    </div>
  );
};

How can I manage to implement the multiple selection in this react app?

2

2 Answers 2

1

I solved it with this one:


  const updateFieldChanged =  e => {

    console.log('property name: '+ e.target.name);
    let newArr = [...categories]; // copying the old datas array
    newArr.push(e.target.value); // replace e.target.value with whatever you want to change it to
  
    setCategories(newArr);
  }
Sign up to request clarification or add additional context in comments.

Comments

1

You could also use the .concat method. It returns a new array as not manipulated state.

setCategories(categories.concat(e.target.name));

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.