0

I have a Form with a couple Form.Select attributes. My onChange() works for the <Form.Select> attributes without multiple set. However, it cannot handle selections from <Form.Select> attributes that do have multiple set.

I would like to have a single onChange function that can handle data changing for instances of Form.Select with or without the "multiple" flag set.

The Form Class:

class SomeForm extends React.Component {
    handleSubmit = event => {
        event.preventDefault();
        this.props.onSubmit(this.state);
    };


    onChange = event => {
        const {
            target: { name, value }
        } = event;

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

        console.log("name: " + name)
        console.log("value: " + value)
    };

    render() {
        return (
            <Form onSubmit={this.handleSubmit} onChange={this.onChange}>

                <Form.Select label="Size" options={sizes} placeholder="size" name="size" />

                <Form.Select
                    label="Bit Flags"
                    placeholder="Bit flags"
                    name="flags"
                    fluid
                    multiple
                    search
                    selection
                    options={bits}
                />

                <Form.Button type="submit">Submit</Form.Button>
            </Form>
        );
    }
}

The logs are never called when I select options from the Form with multiple set.

Some possible bits to populate the options prop of Form.Select:

const bits = [
    {key: '1', text: "some text 1", value: "some_text_1"},
    {key: '2', text:  "some text 2", value:  "some_text_2"},
];

How can I modify onChange() to handle both Form.Select attributes as listed above?

Please note that this question is different from question on StackOverflow which are concerned only with an onChange that can only be used for updating an array.

buratino
  • 1,408
  • 2
  • 17
  • 40

1 Answers1

2

Multiple selects are a weird beast. This post describes how to retrieve the selected values.

If you want to define a form-level handler, you need to make an exception for multiple selects:

    const onChange = (event) => {
        const value = isMultipleSelect(event.target)
          ? getSelectedValuesFromMultipleSelect(event.target)
          : event.target.value
        this.setState({[event.target.name]: value})
    };

    const isMultipleSelect = (selectTag) => selectTag.tagName === 'SELECT' && selectTag.multiple

    const getSelectedValuesFromMultipleSelect = (selectTag) => [...selectTag.options].filter(o => o.selected).map(o => o.value)
Matthieu Libeer
  • 2,286
  • 1
  • 12
  • 16