0

I'm trying to expand the handleInputChange method from https://reactjs.org/docs/forms.html so that it handles a multiple select element. I gather I can get the values following the advice from Retrieving value from <select> with multiple option in React but I need a way to determine that I have a multiple select from the event object that’s passed in and I’m too inexperienced with JS to know how to do this. All the sample code I’ve found assumes that the method knows where its event is coming from.

Don Hosek
  • 981
  • 6
  • 23

1 Answers1

0

The secret sauce turns out to be event.target.type The following code works for all of my input fields for updating state:

    handleInputChange(event) {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked :
                      target.type === 'select-multiple' ? Array.from(target.selectedOptions, option => option.value)
                          : target.value;
        const name = target.name;

        this.setState({
            [name]: value
        });

    }
Don Hosek
  • 981
  • 6
  • 23