Search code examples
javascriptreactjsinputinput-mask

implementation of react-input-mask


I'm using React with reatstrap and, I need to use some type of input mask, to prevent the user from typing characters in the field, and to make an indentation for monetary values (example = $ 10.00)

I found this library: https://www.npmjs.com/package/react-currency-masked-input

I tried this code:

  <CurrencyInput className = "form-control" value = {this.state.input_value}
              onChange = {
                      e => this.setState (
                          {input_value: e.target.value, input_value_per_numb_days: e.target.value / this.state.numb_days}
                      )
                  }
              />

however, it doesn't work, it just changes my field type to number. How can I use this mask to handle the entered values?


Solution

  • according to "Docs"

    Usage notes:
    Calls onChange prop after updating its internal value. First argument is the original event, the second is the masked value.

    The onChange event got a second argument with the masked value:

    
    export default function App() {
      const [input, setInput] = useState();
      const [numbDays, setNumbDays] = useState(0);
    
      const numberOfDays = 7;
    
      const maskInput = (e, masked) => {
        setInput(masked);
        setNumbDays(masked / numberOfDays);
      }
    
      return (
        <div className="App">
          <CurrencyInput name="myInput" onChange={maskInput} value={input} required />
          <h1>input / {numberOfDays} = {numbDays}</h1>
        </div>
      );
    }