How to get a typed value from an Input?

Sophie picture Sophie · Dec 12, 2017 · Viewed 9.5k times · Source

I would like to get a typed value from a ReactStrap Input component, via the onChange function. The aim is to use a text input only but be able to get a specific typed value (String or Number in my example below).

<Input valueAs="String" name="input1" type="text" onChange={this.onChange}></Input>
<Input valueAs="Number" name="input2" type="text" onChange={this.onChange}></Input>

You can see the expected type is defined by the valueAs attribute. I expect to get an event in this.onChange with:

  • a value as a String for Input 1
  • a value as a Number for Input 2

What is the best way to do this with React / Reactstrap?

Answer

iamawebgeek picture iamawebgeek · Feb 28, 2018

Input component of reactstrap does not have a property called valueAs. To get value in a format you need, you can do:

<Input name="input1" type="text" onChange={(e) => this.onChange(`${e.target.value}`)}/>
{/* to make it integer you can add unary plus sign like so: */}
{/* this.onChange(+e.target.value) */}