Positioning the label for a Material-UI text field with an icon adornment when the shrink property is set

https://i.stack.imgur.com/E85yj.png

Utilizing Material-UI's TextField, I have an Icon embedded within. The issue arises when the label "Your good name here" overlaps the icon instead of being placed beside it.

This problem emerged after I included

 InputLabelProps={{ shrink: false }}
in the TextField.

Seeking advice on how to properly adjust the position?

Thank you for any assistance provided! =)

Here is my code pen

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Input from "@material-ui/core/Input";
import InputLabel from "@material-ui/core/InputLabel";
import InputAdornment from "@material-ui/core/InputAdornment";
import FormControl from "@material-ui/core/FormControl";
import TextField from "@material-ui/core/TextField";
import Grid from "@material-ui/core/Grid";
import AccountCircle from "@material-ui/icons/AccountCircle";

const useStyles = makeStyles((theme) => ({
  margin: {
    margin: theme.spacing(1)
  }
}));

export default function InputWithIcon() {
  const classes = useStyles();

  return (
    <div>
      <TextField
        className={classes.margin}
        id="input-with-icon-textfield"
        label="Your good name here"
        InputLabelProps={{ shrink: false }}
        InputProps={{
          startAdornment: (
            <InputAdornment position="start">
              <AccountCircle />
            </InputAdornment>
          )
        }}
      />
      <TextField
        className={classes.margin}
        id="input-with-icon-textfield"
        label="Your good name here"
        // InputLabelProps={{ shrink: false }}
        InputProps={{
          startAdornment: (
            <InputAdornment position="start">
              <AccountCircle />
            </InputAdornment>
          )
        }}
      />
    </div>
  );
}

Answer №1

If you're looking for the default styles for the label, check out the relevant default styles below:

  formControl: {
    position: 'absolute',
    left: 0,
    top: 0,
    transform: 'translate(0, 24px) scale(1)',
  },
  /* Styles applied to the `input` element if `shrink={true}`. */
  shrink: {
    transform: 'translate(0, 1.5px) scale(0.75)',
    transformOrigin: 'top left',
  },

To adjust the label positioning when considering the input adornment width, focus on modifying the x-axis in the translate CSS (e.g. translate(32px, 24px) scale(1)).

Here's a functional example based on your sandbox setup:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import InputAdornment from "@material-ui/core/InputAdornment";
import TextField from "@material-ui/core/TextField";
import AccountCircle from "@material-ui/icons/AccountCircle";

const useStyles = makeStyles((theme) => ({
  margin: {
    margin: theme.spacing(1)
  },
  inputLabelNoShrink: {
    transform: "translate(32px, 24px) scale(1)"
  }
}));

export default function InputWithIcon() {
  const classes = useStyles();
  const [value, setValue] = React.useState("");
  const shrink = value.length > 0;
  return (
    <div>
      <TextField
        className={classes.margin}
        id="input-with-icon-textfield"
        label="Your good name here"
        value={value}
        onChange={(event) => setValue(event.target.value)}
        InputLabelProps={{
          shrink: shrink,
          className: shrink ? undefined : classes.inputLabelNoShrink
        }}
        InputProps={{
          startAdornment: (
            <InputAdornment position="start">
              <AccountCircle />
            </InputAdornment>
          )
        }}
      />
    </div>
  );
}

https://codesandbox.io/s/label-position-with-input-adornment-up0jg?fontsize=14&hidenavigation=1&theme=dark

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

converting HTML values to TypeScript

I'm a beginner with Angular and could use some assistance. Currently, I have two components - one for the index and another for navigation. Within the index component, there are subcomponents that change based on the value of a variable called produ ...

The jQuery onchange function does not have the ability to limit the input to only

When using the script to sum the input value, everything seems to be working fine. However, I am facing an issue where clicking up and down on the "input#total_selfmark" does not change the value. Additionally, when I manually type in a number, the "input# ...

Refreshing the v-model in a child component

Within my parent component, the code structure is similar to this: <template> <ProductCounter v-model="formData.productCount" label="product count" /> </template> <script setup> const initialFormData = { ...

Issue Encountered While Attempting to Show a Div Element within a Function

Check out this HTML code snippet: <div class="div1" id ="div1" onclick="onStepClicked()" style ="text-align:center">Step 1</div> And here is the corresponding Script: function onStepClicked() { var elem = document.getElementById(&apo ...

When using nextjs, there is an issue that arises when attempting to define the property 'id' using context.params.id. This results in

Attempting to retrieve data from a JSON file (response.json) hosted on localhost:8000/response.json. Below is the code snippet from pages/test.js: import React from "react"; import Link from "next/link"; import Image from "next/ima ...

Ensuring Uniform Data Types Across Objects (Using Typescript)

After much trial and error, I have finally reached this point where everything seems to be working perfectly. function test<types extends Record<string,any>>(dict: dictionary<types>){} type dictionary<types extends Record<string, a ...

When the JSON array is converted into a string, it appears as undefined

Below is a snippet of my service.spec.ts file: service.spec.ts it('should mock the http requests', inject([Service, MockBackend], (service, mockBackend) => { let result:any; mockBackend.connections.subscribe((connection) => { ...

Ways to solve the issue of MUI Snackbar/Toast flickering during onHide event

I want to display a Snackbar/Toast when a button is clicked and then have it disappear after a few seconds. However, I'm experiencing an issue where the Snackbar flickers without any text once it disappears. How can I solve this problem? For referenc ...

Load image asynchronously using a mirror server in React/Next.js with a set timeout time

For my website, I have decided to store all of my images on IPFS, which are pinned successfully. This has helped reduce traffic and keep costs within the free tier offered by my hosting provider. However, at times the IPFS url may not load fast enough dep ...

A guide on navigating through nested JSON objects with the help of async.js

Having recently transitioned from a Python background to nodeJS/Javascript's asynchronous nature, I am exploring how to traverse a nested JSON object and extract its values using async.js. In my quest for answers, I stumbled upon this helpful snippet ...

Building a personalized React component poses challenges when working with MUI REACT interfaces

I am looking to develop a unique component that will display two different elements, an icon, and a title. However, I seem to be encountering errors from TypeScript regarding the declaration of my interface. The error message reads: Property 'map&apos ...

Click to Resize Window with the Same Dimensions

I have a link on my website that opens a floating window containing more links when clicked. <a href='javascript:void(0);' onclick='window.open("http://mylink.html","ZenPad","width=150, height=900");' target='ZenPad'>&l ...

How can I exclude multiple recipients when using Pusher?

When using pusher.trigger, only one socket_id can be specified to send an event to a single user. Is there a way to exclude multiple users by specifying their individual socket ids? ...

The $http function in AngularJS consistently returns undefined instead of the expected value

var result = dataService.makeHttpRequest("GET", "/documents/checkfilename/", null, function (response, status, headers, config) { // I can see `true` if I alert(response); here // I want to return the contents of ...

json data hidden from sight in jQuery

Snippet of HTML Code: <select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);"> <option value="">--Select--</option> <option value="Value11">Value1</option> <option value="Value2">Value2</op ...

Using Ajax.BeginForm with BeforeSend functionality

My MVC website has multiple Ajax.BeginForm elements, and I am looking to handle the beforeSend event of my Ajax calls. While the code below works for manual jquery ajax calls, it does not seem to work with the Ajax.BeginForm helpers: $.ajaxSetup({ &a ...

Is it possible to constantly retrieve data at one-second intervals in NextJS using getServerSideProps?

Is there a way to continuously fetch API data in NextJS using SSR (getServerSideProps) every second? This would involve the client making a request to the server every one second to receive the most up-to-date API data. Any suggestions? export const getS ...

Step-by-step guide: Creating a captivating triangular shape on the current tab

I am trying to implement a dynamic tab using Bootstrap where clicking on a tab will display a thicker black underline, like in this image: https://i.stack.imgur.com/h48GB.png To achieve the black line effect, I have added the following code: .nav-tabs.n ...

Issue: An incorrect hook call occurred. How can data from one hook be awaited before being instantiated into another?

Hey there, I'm currently working on injecting a header into my fetcher before using swr to fetch the data. The challenge is that I need to await for a custom hook to respond with the data before injecting it into the custom fetcher. I've noticed ...

Converting Selenium Webdriver Xpath value to CSS: A Step-by-Step

We are looking to transform the lengthy HTML Xpath values in the existing code into a shorter CSS value: driver.findElement(By.cssSelector(".form button")).click(); ...