Create an input allowing only float numbers in React

Let's assume that you want to create an input in React where the user can only type float numbers. First, you need to check if the number has a _._ pattern.

You can use RegEx to check it:

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

Now, imagine that a user wrote 09 or .9. You want to display it as 9 or 0.9. Thus, when the input is out of focus, you need to transform the input into a float using the parseFloat() function.

Example:

jsx
import React, { useState } from 'react'

const floatInput = () => {

    const [number, setNumber] = useState('')

    const handleNumber = (e) => {

        let input = e.target.value

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

    }

    const handleFloat = () => {

        // The conditional prevents parseFloat(null) = NaN (when the user deletes the input)
        setNumber(parseFloat(number) || '')

    }

    return <input placeholder = 'Type number...' value = {number} onChange = {handleNumber} onBlur = {handleFloat}/>

}

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