Home > database >  React form handle multiple selection
React form handle multiple selection

Time:03-27

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?

CodePudding user response:

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

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

CodePudding user response:

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);
  }
  • Related