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

Add motion to the div element when hovering and moving the mouse away

Looking to add animation to a list moving from left to right and vice versa. Now, I want the list to animate from left to right when the mouse hovers over the div, and then animate from right to left when the mouse leaves the div. Can someone assist me wit ...

What is the best way to position a logo and navbar in alignment?

I'm still learning the ropes here. I'm having trouble getting the navbar to align with the logo because margin-top/bottom doesn't seem to be working for some reason. <HTML> <HEAD> <link href="style.css" rel="stylesheet"&g ...

Access dynamic content from Tinymce 4.x without any manual effort

Is there a way to extract the HTML content from a tinyMCE editor and display it on a page without using the tinyMCE editor itself? I know about the getcontent() function in tinyMCE, but is there another function, parameter, or plugin that can be used to ...

The jQuery scrollLeft function seems to be stuck and not working correctly

I have a container div with a ul inside of it set up like this CodePen: http://codepen.io/example/123 Why won't the scroll feature work? HTML: <div id="container"> <ul class="list"> <li>apple</li> <li>orange& ...

What advantages and disadvantages come with choosing between using vh and vw for responsive text?

My main inquiry is centered around the various techniques for creating responsive text. Is there a particular method that stands out as the best option for general use, or do different methods serve distinct purposes? ...

Having difficulty transforming both scale and box-shadow at the same time

Is there a way to animate the circle's box-shadow while also scaling it down from 1.6x to 1 during the same transition period? I'm having trouble with the timing of the scale animation, as it seems to occur after the box-shadow animation is fini ...

The issue of deleting the incorrect document ID in React Firebase

I'm currently facing an issue while trying to implement a delete operation on a Firebase database using Reactjs. The problem lies in my function that seems to be fetching the wrong id from Firebase. There's a button triggering the handleOpen fun ...

Tips for monitoring input content "live"

Currently, I am in the process of developing a web form that includes a text field intended to receive numeric values. If the user enters non-numeric characters into this field, the form will not submit. However, there is no error message displayed to noti ...

Improving the layout of text by adjusting the width within a flex-box styled card

I have a card with the style property "display: flex;" applied to it along with other stylings, all of which are checked in the snippet below. My goal is for the text within the card to move to a new line once its width reaches either 120px or 7 ...

When multiple checkboxes are selected, corresponding form fields should dynamically appear based on the checkboxes selected. I attempted to achieve this functionality using the select option method

Require checkboxes instead of a selection option and have multiple checkbox options. Depending on the checked checkboxes, different form fields should appear. A submit button is needed. I have included some CSS code, but a more detailed CSS code is requir ...

Using AngularJS to retrieve DOM elements within a directive's controller

Currently, I am in the process of creating a custom image carousel directive using only AngularJS and no additional libraries. simpleCarousel.$inject = []; function simpleCarousel() { var directive = { restrict: 'E', templat ...

Tips on showcasing the elements within a div container using flexbox

Seeking advice on positioning items/cards using flexbox in my initial react app. The issue lies with the div within my card component where applying display: flex; turns every card into a block (column-like) structure, flexing only the content within each ...

How can I disable auto-fill for password input fields? Setting autocomplete="off" doesn't seem to be working

Hey there, I'm having some trouble with the autocomplete feature in Google Chrome. Can anyone suggest an alternative way to disable autocomplete for password fields? By the way, my project is using Vue.js. ...

Overflow - conceal the scrollbar and prevent scrolling without cutting off the element

Whenever I implement the code snippet below: body { overflow: hidden; } The overflowing element gets clipped. However, when I try this code instead: body { overflow: auto; } The element is no longer clipped, but now a scrollbar appears where it ...

Hover Link Overlay [CSS / HTML] - An Alternative Style for Link Interaction

I'm having trouble making an image clickable within a hover effect overlay that displays text and a link. I attempted to turn the overlay into a link, but it wasn't successful. http://jsfiddle.net/cno63gny/ Please disregard the placeholder text ...

Issue with Brave browser: CSS animations not functioning properly, although they work perfectly in Firefox

Link to Codepen: https://codepen.io/sabeser/pen/RwYzJpd HTML: <div id='wrapper'> <div class='circle'></div> <div class='circle'></div> </div> CSS: :root { --scale--rati ...

Why do I see my footer displayed twice on the page?

<div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li> @Ajax.ActionLink("Imagenes List", "Images", "Home", new { page = 0 }, new AjaxOptions() ...

When using Vue.js, the class binding feature may not function properly if it is referencing another data property that has variants

I am currently developing a basic TODO application. Within my index.html file, I have a main div with the id #app. Inside this div, there is another div with the class .todobox where I intend to display different tasks stored in my main.js file. Each task ...

Considering upgrading material-ui from version 14.4 to 16.2 - Should we use the hoc/selectable-enhance?

Currently in the process of upgrading a codebase from material-ui version 0.14.4 to 0.16.2. Successfully updated all components except for: material-ui/lib/hoc/selectable-enhance This particular component is implemented in the existing codebase like so: ...

Exploring the possibilities of device orientation in combination with 3D transforms

Imagine a project that aims to create a cube with sides representing different geolocations. The cube's sides for east, west, up, ground, north, and south are meant to always point in their respective directions. To gather the necessary data, the proj ...