episodewon
episodewon

Reputation: 29

React input select to display corresponding components & select string value to number value

I am populating a select list and drawing the corresponding information component from the same json. Select is set up with .map and all the correct values.. (I think). onChange is assigned to countryChange which takes a event value and setStates to pass on a trigger.

What I don't understand is, 1. e.target.value is a string instead of a number, 2. while a state assigned to 0, e.target.value and the state return a different value...

this.state={
 selectedCountry:0
}



      countryChange( e ) {
            const list = e.target.value;
            const countrylist = this.props.countries.find(c => c.id === list)
              this.setState({
                    selectedCountry: countrylist
                   // selectedCountry: parseInt(e.target.value, 10) 
                });
            }
        render() {
                    return(
                      <select id="exampleSelect" onChange={this.countryChange.bind(this)}>
                      <option value="d">Select Country</option>
                     {this.props.countries.map((item) => ( <option key={item.id} value={item.id}> { item.name } </option> ))}</select>

after, I send the selectedCountry as props to other components to render information. I've been looking at other similar questions and answers and came this far but can't seem to fully execute it the way I want.

Upvotes: 0

Views: 540

Answers (1)

Andy Taton
Andy Taton

Reputation: 491

For HTML <option> elements, the value attribute is interpreted by browsers as a string. (HTML specifications describe it as type DOMString.) It looks like you have already figured out that you need to convert this to a number if you want it to be a number, but I think you've done it a bit late to make your comparisons work. How about

const list = parseInt(e.target.value);

as the first line of countryChange instead?

Alternately, you could just make all of your comparisons string comparisons. You would probably want your .id properties to be strings, and you'd want your initial setState to make {selectedCountry: "0"}.

Upvotes: 1

Related Questions