material-ui-currency-textfield icon indicating copy to clipboard operation
material-ui-currency-textfield copied to clipboard

couldn't work with mui version 5

Open Nidhi-Vedaha opened this issue 3 years ago • 4 comments

Nidhi-Vedaha avatar Feb 25 '22 04:02 Nidhi-Vedaha

We're all waiting for @merlos or @sureshsevarthi to merge pull request #43 to update it to be compatible with MUI v5

alext9586 avatar Feb 25 '22 18:02 alext9586

related to #43 and #39

GhostyJade avatar Feb 25 '22 21:02 GhostyJade

This works with MUI 5, and was my solution. Not as many features as the actual plugin, but largely accomplishes the same thing.

Info on toLocaleString can be found here. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

const setPrice = (e) => {
    setPrice(e.target.value.replace(/[^0-9\.]/gi, ""));
  };

const convertPrice = () => {
    let tempPrice = Number(price).toLocaleString("en-EN", {
      style: "currency",
      currency: "USD",
    });
    setPrice(tempPrice);
  };
<TextField
value={price}
onChange={setPrice}
onBlur={convertPrice} />

SerbianLastName avatar Feb 26 '22 07:02 SerbianLastName

This works with MUI 5, and was my solution. Not as many features as the actual plugin, but largely accomplishes the same thing.

Info on toLocaleString can be found here. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

const setPrice = (e) => {
    setPrice(e.target.value.replace(/[^0-9\.]/gi, ""));
  };

const convertPrice = () => {
    let tempPrice = Number(price).toLocaleString("en-EN", {
      style: "currency",
      currency: "USD",
    });
    setPrice(tempPrice);
  };
<TextField
value={price}
onChange={setPrice}
onBlur={convertPrice} />

Thank you for this. I would suggest adding the following though. First issue is this solution allows a user to enter multiple periods (eg: 50000.12.4141.1212) which will result in NaN when passed to Intl.toLocaleString. Simply test if there is more than one period, split the string by periods, and only return the first 2 results (dollars, cents) to make a clean string.

if (tempPrice.match(/\./g).length > 1) {
    const [dollars, cents] = tempPrice.split('.')
    tempPrice = `${dollars}.${cents}`
}

Next the solution will always return the string with a leading $. Since you probably don't want this in your data, you can strip it with

tempPrice = tempPrice.replace(/\$/g, '')

Putting it all together with the original solution, your onBlur will look like:

const convertPrice = () => {
    let tempPrice = price

    if (tempPrice.match(/\./g).length > 1) {
        const [dollars, cents] = tempPrice.split('.')
        tempPrice = `${dollars}.${cents}`
    }

    tempPrice = Number(tempPrice).toLocaleString('en-EN', {
        style: 'currency',
        currency: 'USD',
    })

    tempPrice = tempPrice.replace(/\$/g, '')

    setPrice(tempPrice)
}

cyoung502 avatar Oct 21 '22 16:10 cyoung502