Add Suffix Follow By User Input Material Ui TextField
I want to create TextField element that has value when user key in followed by Input Adornment. Is it possible to add % sign after value instead of end of input ? Currently percent
Solution 1:
I think adornments are not the best approach for this problem. Instead you should look at the Integration with 3rd party input libraries example in the documentation.
Here is a modified version of the TypeScript code for the demo using the "react-number-format" package to add a % suffix:
import * as React from "react";
import NumberFormat from "react-number-format";
import TextField from "@mui/material/TextField";
interface CustomProps {
  onChange: (event: { target: { name: string; value: string } }) => void;
  name: string;
}
const NumberFormatCustom = React.forwardRef<NumberFormat, CustomProps>(
  function NumberFormatCustom(props, ref) {
    const { onChange, ...other } = props;
    return (
      <NumberFormat
        {...other}
        getInputRef={ref}
        onValueChange={(values) => {
          onChange({
            target: {
              name: props.name,
              value: values.value
            }
          });
        }}
        thousandSeparator
        isNumericString
        suffix="%"
      />
    );
  }
);
interface State {
  numberformat: string;
}
export default function FormattedInputs() {
  const [values, setValues] = React.useState<State>({
    numberformat: "90"
  });
  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setValues({
      ...values,
      [event.target.name]: event.target.value
    });
  };
  return (
    <TextField
      sx={{ maxWidth: 120 }}
      label="Percentage"
      value={values.numberformat}
      onChange={handleChange}
      name="numberformat"
      id="formatted-numberformat-input"
      InputProps={{
        inputComponent: NumberFormatCustom as any
      }}
      variant="standard"
    />
  );
}
Post a Comment for "Add Suffix Follow By User Input Material Ui TextField"