Transform input into a value (when it's a number) in React

Let's suppose that you want to transform an input to a number (if it's a number). Otherwise, keep the input as a string. You want to transform the field while the user is typing on the input.

You can use the following Regex pattern to match the cases such as {number}.{number}:

/^[0-9]{1,}(\.[0-9]{1,})?$/

This is the React component:

jsx
import React, { useState } from 'react';

const Input = () => {

    const [field, setField] = useState('');

    const handleInput = (e) => {

        let input = e.target.value;

        if(input.match(/^[0-9]{1,}(\.[0-9]{1,})?$/))
            input = parseFloat(input);

        setField(input);

    }

    return(
        <input 
            onChange    = {handleInput} 
            placeholder = {'Whatever...'} 
            value       = {field}
        />
    );

}

export default Input;

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.