7

Is it possible to have Material-UI automatically adjust the width of the TextField element to match the width of the input text?

I am creating a form view/edit page and I'm rendering the data back into the same fields, however there is also a series of parameters which the server sets. It would be nice to render in disabled form elements and have their width automatically fit.

I've played with the width properly of both TextField and the underlying Input with no success. I could potentially count the characters and set a width in JS, but I'd rather a CSS solution.

<TextField
    disabled={true}
    label={"UUID"}
    value={"7be093a5647d41ff8d958928b63d11f5"}
    style={{width: "auto"}}
    InputProps={{
        style: {width: "100%"}
    }}
/>

https://codesandbox.io/s/material-demo-forked-c3llv

User
  • 339
  • 5
  • 16

1 Answers1

8

You could base the width of the input on the length of the text

const FONT_SIZE = 9
const DEFAULT_INPUT_WIDTH = 200

const [textValue, setTextValue] = useState("")
const [inputWidth, setInputWidth] = useState(DEFAULT_INPUT_WIDTH)

useEffect(() => {
  if (textValue.length * FONT_SIZE > DEFAULT_INPUT_WIDTH) {
    setInputWidth((textValue.length + 1) * FONT_SIZE)
  } else {
    setInputWidth(DEFAULT_INPUT_WIDTH)
  }
}, [textValue])

return (
  <div>
    <TextField
      label={"UUID"}
      value={textValue}
      onChange={(e) => setTextValue(e.target.value)}
      InputProps={{
        style: { width: `${inputWidth}px` },
      }}
    />
  </div>
)

Below is the forked codesandbox

Edit Material demo (forked)

Reference: this answer

hgb123
  • 13,869
  • 3
  • 20
  • 38
  • Thanks a lot for this answer! Is it possible to do the same for Material-UI Autocomplete? https://stackoverflow.com/questions/64121557/how-to-change-width-of-materialui-autocomplete-based-on-option-selected – Raisa A Sep 30 '20 at 06:27