Skip to content
Advertisement

Sending number instead of string from Select in React component

I have a “controlled” React component for a very simple drop down that looks like this:

JavaScript

Initially, I set the value of the field to 0 in my reducer. This is the right thing to do because the value will always be a number. The problem I’m having is this:

Initially, everything is fine but when I make a selection, I get a warning saying an invalid prop of type string is supplied and it was expecting a number.

How do I make sure the values in the options are numbers and not strings?

BTW, I tried not using quotes for option values but React doesn’t seem to like it i.e. <option value=1>Apples</option>

Advertisement

Answer

I assume your handleChange looks something like this

JavaScript

The issue here is that html needs quotes around the attribute values, so in essence e.target.value resolves to a string. A simple fix would be to parse it into a number by using

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement