unicef / material-ui-currency-textfield

Currency textfield for React Material UI
https://unicef.github.io/material-ui-currency-textfield/
117 stars 93 forks source link

couldn't work with mui version 5 #54

Open Nidhi-Vedaha opened 2 years ago

alext9586 commented 2 years ago

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

GhostyJade commented 2 years ago

related to #43 and #39

SerbianLastName commented 2 years ago

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} />
cyoung502 commented 2 years ago

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)
}