Search code examples
javascriptarraysreactjsstateselect-options

How can i update select option from state in react.js


I created an input, when you write something and click on the button, value adds to our state, now I am trying to update select option from state like this:

const NewGroup = () => {
  const [group, setGroup] = useState([]);
  const addToGroup = (e) => {
    const newGroup = group;
    newGroup.push(e.target.previousElementSibling.value);
    setGroup(newGroup);
  };
  return (
    <div>
      <input type="text" name="" id="" />
      <button onClick={addToGroup}>submit</button>
      <div>
        <select name="" id="">
          {group.map((category) => {
            return <option value=''>{category}</option>;
          })}
        </select>
      </div>
    </div>
  );
};
export default NewGroup;

But nothing did happened.


Solution

  • You can introduce another useState() for writing into <input> element. And when the Submit button is pressed, you only push the someText to the group array.

    const NewGroup = () => {
      const [group, setGroup] = useState([]);
      const [someText, setSomeText] = useState("");
      const addToGroup = (e) => {
        // Takes up all the present elements(of array group) and adds new element (search)
        let temp = [...group, someText];
        setGroup(temp);
      };
      return (
        <div>
          <input type="text" name="" id="" value={someText} onChange={(e) => { setSomeText(e.target.value); }} />
          <button onClick={addToGroup}>submit</button>
          <div>
            <select name="" id="">
              {group.map((category, index) => {
                return (
                  <option key={index} value="">
                    {category}
                  </option>
                );
              })}
            </select>
          </div>
        </div>
      );
    }
    
    export default NewGroup;
    

    Here's the link to the working app https://codesandbox.io/s/boring-ptolemy-0cwzmi?file=/src/App.js