How to smoothly apply currency mask in MUI DataGrid?

32 Views Asked by At

I'm trying to apply the monetary mask inside editable cells, not with a final value, but after every digit.

I almost have success utilizando Intl.NumberFormat, but they don't get smoothly.

I am trying:

  const formatToDecimal = (value: string = "0") => {
    return parseFloat(value.replace(/[^0-9,]*/g, "").replace(",", ".")).toFixed(
      2
    );
  };

  const formatCurrency = (value) => {
    console.log(value);
    if (!value) return "R$ 0,00";
    let teste = formatToDecimal(value.replace(/[^0-9.,]/g, ""));

    return new Intl.NumberFormat("pt-BR", {
      style: "currency",
      currency: "BRL",
    }).format(teste);
  };

  const columns: GridColDef[] = [
    { field: "name", headerName: "Name", width: 180, editable: true },
    {
      field: "currency",
      headerName: "Currency",
      // type: "number",
      width: 180,
      editable: true,
      valueFormatter: (params: GridValueFormatterParams<number>) => {
        if (params.value == null) {
          return "R$ 0,00";
        }
        return params.value.toLocaleString("pt-BR", {
          style: "currency",
          currency: "BRL",
        });
      },
      valueParser: (newValue) => {
        return formatCurrency(newValue);
      },
    },
  ];

It works, but the user has to use the arrows or mouse to create the correct formatted number.

I use the valueParser to modify entered values.

Readind the docs: "You can use the valueParser property in the column definition to modify the value entered by the user..." https://mui.com/x/react-data-grid/editing/#value-parser-and-value-setter

My test: https://codesandbox.io/p/sandbox/elegant-napier-nwt2ss?file=%2Fsrc%2FDemo.tsx%3A112%2C29

0

There are 0 best solutions below