Search code examples
javascriptnode.jsreactjsreactstrap

Retrieving array of values from react select form


So basically I'm attempting to create a form with a select dropdown box. I'm trying to send an array of values to the onChange function through the value property, but it just gives me a string instead. How can I pass the values back and access them in an array style?

The reactjs site shows that this is possible under the select Tag, but not how to access the values...

https://reactjs.org/docs/forms.html#the-select-tag

    <Input type="select" name="university" id="university" onChange={this.onSelect}>

    {this.props.universities.universities.map(({ idUniversity, name}) => (
       <option key ={idUniversity} value = {[idUniversity , name]}>
         {name}
       </option>
    ))}

    </Input>

    onSelect = (e) => {
        console.log(e.target.value[0] + " " + e.target.value[1] );
        this.setState({
            university_id: e.target.value[0],
            university_name: e.target.value[1]
        });
    }

When I run this, e.target.value[0] gives me the first character of the entire string given by {[idUniversity , name]}.

So for example, the array should be [2, University of Central Florida], but e.target.value[0] will return just [


Solution

  • This answer has some possible ways of going about it using the index to select the items from your initial data, however in your case it might just be easiest to split the value back into array form:

    onSelect = (e) => {
        const [university_id, university_name] = e.target.value.split(',');
    
        this.setState({
            university_id,
            university_name,
        });
    }