I have a “controlled” React component for a very simple drop down that looks like this:
const MyDropDown = ({field, handleChange}) => { return( <select name="myField" value={field} onChange={handleChange}> <option value="1">Apples</option> <option value="2">Oranges<option> <option value="3">Bananas</option> <select> ); } MyDropDown.propTypes = { field: PropTypes.number.isRequired, handleChange: PropTypes.func.isRequired } export default MyDropDown;
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
handleChange(e) { this.setState({ val: e.target.value}); }
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
parseInt(e.target.value, 10);