Bean
Bean

Reputation: 218

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 percentage sign(%) is at start of input before user key in and will go to end of input if there is value.

<TextField
{...defaultProps}
InputProps={{
    startAdornment: this.state.percentage ? (
        <span />
    ) : (
        <InputAdornment position='start'>%</InputAdornment>
    ),
    endAdornment: this.state.percentage ? (
        <InputAdornment position='end'>%</InputAdornment>
    ) : (
        <span />
    ),
    classes: defaultInputClasses
}}
error={this.state.percentageError ? true : false}
fullWidth
helperText={this.state.percentageError ? 'percentage must be between 1-100' : ''}
id='percentage'
label='percentage'
margin='normal'
name='percentage'
onChange={this.handleChange}
value={this.state.percentage}

/>

Initial state

initial

Current state when user key in

keyIn

Expected

expected

Upvotes: 8

Views: 15921

Answers (1)

Ryan Cogswell
Ryan Cogswell

Reputation: 80986

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"
    />
  );
}

Edit FormattedInputs Material Demo

Upvotes: 11

Related Questions