[javascript] Only numbers. Input number in React

Here is a solution with onBlur, it can be very helpful as it also allows you to format the number the way you need it without requiring any black magic or external library.

2020 React Hooks

const toNumber = (value: string | number) => {
    if (typeof value === 'number') return value
    return parseInt(value.replace(/[^\d]+/g, ''))
}

const formatPrice = (price: string | number) => {
  return new Intl.NumberFormat('es-PY').format(toNumber(price))
}
<input
    defaultValue={formatPrice(price)}
    onBlur={e => {
      const numberValue = toNumber(e.target.value)
      setPrice(numberValue)
      e.target.value = formatPrice(numberValue)
    }}
    type='tel'
    required
/>

How it works:

  • Set initial value via defaultValue
  • Allow user to freely type anything they feel
  • onBlur (once the input looses focus):
    • replace any character that is not a digit with an empty string
    • setState() or dispatch() to manage state
    • set the value of the input field to the numeric value and apply optional formatting

Pay attention: In case your value come from a async source (e.g. fetch): Since defaultValue will only set the value on the first render, you need to make sure to render the component only once the data is there.

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release