React Material UI Textfield with Thousands Separator

460 views Asked by At

I want to format my textfield with a $ and thousands separators. I.e. $120,000 instead of 120000. I get two warnings:

1.) Warning: Failed prop type: The prop name is marked as required in ForwardRef(NumericFormatCustom), but its value is undefined. at NumericFormatCustom (webpack-internal:///./src/components/TextFieldTest.js:43:26)

However, my name prop is defined.

2.) The specified value "$120,000" cannot be parsed, or is out of range.

When I type a number in my textfield, I get the same warning as #2, with the following console output.

CHANGED {formattedValue: '$6', value: '6', floatValue: 6}

How can I add thousands separators to my Material UI textfield?

import TextField from "@mui/material/TextField";
import React, { useState, useContext } from "react";
import { PropertyContext } from "components/PropertyContext";
import NumericFormat from "react-number-format";

const NumericFormatCustom = React.forwardRef(function NumericFormatCustom(
props,
ref
) {
const { onChange, ...other } = props;

const handleValueChange = (values) => {
    console.log("CHANGED ", values);
    const rawValue = values.value;
    const strippedValue = rawValue.replace(/[$,]/g, "");
    const parsedValue = parseInt(strippedValue);
    onChange({
    target: {
        name: props.name,
        value: parsedValue,
    },
    });
};

return (
    <NumericFormat
    {...other}
    getInputRef={ref}
    onValueChange={handleValueChange}
    thousandSeparator
    isNumericString
    prefix="$"
    />
);
});

export default function TextFieldTest(props) {
const { property } = useContext(PropertyContext);

return (
    <TextField
    label="react-number-format"
    value={values.numberformat}
    onChange={handleChange}
    name="numberformat"
    id="formatted-numberformat-input"
    InputProps={{
        inputComponent: NumericFormatCustom,
    }}
    variant="standard"
    />
);
}
1

There are 1 answers

0
Simran Singh On

As mentioned in react-number-format docs. It is recommended to pass Mui component inside the NumericFormat wrapper component using customInput prop. But you're doing the opposite and trying to inject NumericFormat inside TextField.

Here is a very simple solution ✅:

import { NumericFormat } from 'react-number-format'
import InputAdornment from '@mui/material/InputAdornment'
import TextField from '@mui/material/TextField'
import { useState } from 'react'

const [value, setValue] = useState<number>()

<NumericFormat
    label="My Label"
    value={value}
    customInput={TextField}
    InputProps={{
      startAdornment: <InputAdornment position="start">$</InputAdornment>,
    }}
    allowNegative={false}
    thousandSeparator
    placeholder="0"
    onValueChange={({ value }) => setValue(Number(value))}
  />