DEV Community

CP
CP

Posted on • Edited on

3 1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more