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

Is there a way for Material-UI to adjust the width of the TextField element automatically based on the input text?

When creating a form view/edit page and rendering data into fields, I also have parameters set by the server. It would be convenient to have the disabled form elements automatically adjust their width.

I've tried adjusting the width of both the TextField and Input components without success. One option could be counting the characters in the field and setting the width with JavaScript, but I prefer a CSS solution.

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

Check out this example on CodeSandbox

Answer №1

You can dynamically adjust the input width based 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>
)

Check out the modified codesandbox below:

https://codesandbox.io/s/material-demo-forked-mqdib?fontsize=14&hidenavigation=1&theme=dark

For more information, visit: this answer

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing auto-complete functionality using two keys in Material UI and React

My goal is to enable autocomplete for input when searching with values like title and year. Strangely, the autocomplete feature only works when I search with title. Searching with year does not yield any options. Sample code export default function ComboB ...

The dominance of CSS over other attributes in styling

Imagine having a main body text div and a navigation div for a website. What if you want to make links in the body text green instead of blue, but have the links in the navigation div be red? If you use CSS to make links green, then all links turn green. ...

When using html-pdf-chrome to print to an A4 PDF, there appears to be a significant space below the A

In my Laravel project, I am currently utilizing the westy92 / html-pdf-chrome library to convert HTML to PDF. The front-end of my project is based on React. I have defined a series of divs to act as A4 pages: <div id="pdf" className="pri ...

How can we align divs in the center horizontally inside a parent div?

This question has been asked many times, but I can't seem to figure it out in my situation as I am new to HTML. I have three divs (boxes: QM, Audit, PM) and I want to center them within a parent div called Services. In the photo provided, you can see ...

Creating an HTML table by populating it with data from a JavaScript array

Imagine you have a JavaScript array structured like this: [ "Heading 1", "Heading 2", "Data 1", "Data 2", "Data 3", "Data 4", ] Your task is to generate an HTML table from this array that looks like the one in this link: https://i.stack.imgur.com/7laUR. ...

Best Practices for Validating Form Inputs using react-final-form Across Multiple Screens

Using a combination of react-final-form, material ui, mui-rff, and yup for form validations presents some challenges when dealing with multiple wizard screens. Each screen contains HTML form elements such as inputs and radio buttons that are required for u ...

What can be done to prevent the aspect ratio from being altered?

I am working on creating a parallax effect using a background image that is set to a width of 100% and a height of 700px. I have set the image to have a fixed attachment, but the problem arises when I change the size of the browser window - the picture los ...

Margin ambiguity in a vue.js application

I am facing an issue with my Vue.JS project setup. I want the App.vue to occupy the entire page and have different routes displayed within App.vue using router-view. But, when I try to add a margin to the content of my Game component, the margin seems to ...

Troubleshooting Problems with Material-UI DataGrid Width

Is there a way to limit the width of the DataGrid to match the width of its rows without specifying a width for the containing div? I attempted using disableExtendRowFullWidth={true} but it only affects the row widths, not the overall width of the DataGri ...

The correct method for including a CSS file in a Vue.js application

How can external CSS files be properly added in a Vue.js Application? I have come across multiple methods for adding CSS files in a Vue.js Application. One suggestion is to use the following code: <link rel="stylesheet" type="text/css" href="/static/b ...

"Bootstrap is functioning properly on my local environment, but it seems to

Utilizing the MVC framework and bootstrap has been successful for optimizing my website locally. However, when I upload it to the server, none of the CSS is being rendered. Additionally, the front page, meant to be a carousel slider, appears as a vertical ...

utilize javascript to style iframe from an external domain without access to its DOM structure

I have two websites, example.com and example1.com. I'm trying to display the content of example1.com within an iframe on example.com. For instance: Add this code to example.com: <iframe src='http://example1.com'> Then add the follow ...

I am looking to add some flair to my ID "checkimg" using JavaScript

JavaScript if ((valid1 && valid2 && valid3 & valid4 && valid5 && valid6 && valid7 && valid8)==1) { // include an image in the specified ID. document.formElem.next1.disabled=false; } else { docume ...

Personalized text field in date selector using Material UI

Hey there, I've been incorporating Material UI into my react project, specifically utilizing their recommended Material UI Pickers for a date picker. In order to maintain consistency with the rest of my form fields, I'm attempting to customize th ...

Generate nth-child selectors in a Material-UI component using props dynamically

I am currently working on customizing the Material UI slider component, specifically focusing on its marks prop to display the number of occurrences for each data object within the marks array. The desired appearance of the slider is illustrated in this i ...

Learn how to dynamically highlight a table row when any changes are made to it using jQuery

Is there a way to automatically highlight the current table row when any input text or image is changed within that specific row using jQuery? In the given code snippet below, with two rows provided, how can one of the rows be highlighted upon modifying ...

What is the method to adjust the opacity of a background in CSS without affecting the entire container?

Although it seems simple, I am trying to design a website background with a container that has semi-transparent properties. When I include opacity: 0.5; within the #content code, the entire container, along with its content and text, becomes transparent. ...

Background image that covers the entire page

I am using background-size:cover to ensure that the entire background positioning area is covered by the background image. However, I've noticed that setting it to "cover" sometimes cuts off parts of my background image. Is there another way to achiev ...

Stopping setTimeout when leaving the current page: Is it possible?

Good evening, I am looking for advice on how to cancel a setTimeout function when a user navigates to other pages (for example, by clicking other links or pressing the back button in the browser, but not by changing tabs). I have attempted to use the windo ...

Tips for maintaining consistent formatting of a div element across various sizes

Looking to create a Bootstrap Jumbotron that features a background image, text (h1 and p), and a call-to-action button that scales appropriately for different viewports without sacrificing formatting. Essentially, the goal is for the div to behave like an ...