DEV Community

CP
CP

Posted on • Edited on

Simple Currency Input

Currency input could be laborious to write up from scratch, especially if you want it to have proper formatting inside of the input box.

While you can do it the vanilla way using toLocaleString() and replace(/[^\d.]/gi, '' to clean up the strings in handleChange, I found the react-currency-input-field package that makes it super easy.

Check it out on CodeSandbox or view the source below:

Screenshot



import React, { useState } from "react";
import CurrencyInput from "react-currency-input-field";
// https://www.npmjs.com/package/react-currency-input-field/v/3.0.0-beta.7#v300-release-notes
import "./styles.css";

export default function App() {
  const prefix = "$ ";
  const [value, setValue] = useState(0);

  const handleChange = (e) => {
    e.preventDefault();
    const { value = "" } = e.target;
    const parsedValue = value.replace(/[^\d.]/gi, "");
    setValue(parsedValue);
  };

  const handleOnBlur = () => setValue(Number(value).toFixed(2));

  return (
    <div className="App">
      <h1>Super Simple Currency Input</h1>
      <p>
        Using{" "}
        <a
          href="https://www.npmjs.com/package/react-currency-input-field/v/3.0.0-beta.7#v300-release-notes"
          target="_blank"
          rel="noreferrer"
        >
          react-currency-input-field
        </a>
      </p>
      <CurrencyInput
        prefix={prefix}
        name="currencyInput"
        id="currencyInput"
        data-number-to-fixed="2"
        data-number-stepfactor="100"
        value={value}
        placeholder=""
        onChange={handleChange}
        onBlur={handleOnBlur}
        allowDecimals
        decimalsLimit="2"
        disableAbbreviations
      />
    </div>
  );
}



Enter fullscreen mode Exit fullscreen mode

Top comments (0)