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

How can we stop the navigation submenus (ULs) from appearing as if they are floating?

I've created a navigation bar with an unordered list consisting of smaller unordered lists, each with the class "subnav". When the screen is small, the navigation collapses and the menus stack on top of each other. I want the navigation to maintain i ...

Styling the topbar with CSS includes adding a vertical separator that neatly wraps the content within the

I recently created a website using HTML and CSS, featuring a topbar. However, I encountered an issue while trying to insert a vertical separator between some of the icons within the topbar. Initially, when I added the separator-div, only the first three ic ...

React / Express - Issue: ENOENT: The file or directory specified does not exist: '/app/build/index.html'

Kindly review the following changes: I am desperately seeking help here. After countless hours of sifting through documentation and attempting various methods suggested on this platform, I am still faced with an error during Heroku's build process aft ...

What is the most reliable method for converting a 32-bit unsigned integer to a big endian byte array?

Looking for a simple and reliable method to convert an unsigned integer into a four-byte-array in big endian format, with padding if necessary? Take a look at this example: Input value: 714 Output: Resulting byte array [ 0xca, 0x02, 0x00, 0x00 ]; By the ...

Transform the jQuery UI Slider to be clickable rather than draggable

Currently using jQuery UI 1.10.3 and aiming to create a slider widget that is not draggable. The intention is for the user to click on specific values along the slider instead. I previously attempted using eventDefault in the slider's start method, b ...

Ways to conceal specific content within a text using CSS

Help me with the updated code <html> <title>css</title> <head> <style> #st { z-index: -114; margin-right: -80px; } </style> </head> State Code : <span><span id="st"></span>Maharashtra - MH ...

Creating a platform for users to share their thoughts and engage in

A friend and I are working on creating a commenting system for our website. We have written some code to insert values into a mysql database so that they can be read and displayed as comments later on. Unfortunately, we are facing an issue where the data i ...

Unable to initiate ASP Controller using fetch from React

I have been attempting to initiate an ASP Controller from React, but unfortunately I have not had any success. After trying numerous different approaches, I continue to encounter issues. Sometimes I receive a message in the browser stating that the routes ...

Encountering an error when attempting to parse a JSON Object in Java from an AJAX call

** Latest Code Update ** My JavaScript and Ajax Implementation: $(function() { $("#create_obd").bind("click", function(event) { var soNumber = []; $('#sales_order_lineItems input[type=checkbox]:checked').eac ...

Issue in Ionic 2: typescript: The identifier 'EventStaffLogService' could not be located

I encountered an error after updating the app scripts. Although I've installed the latest version, I am not familiar with typescript. The code used to function properly before I executed the update. cli $ ionic serve Running 'serve:before' ...

Reactjs with JSX: Parsing error unexpected token "<"

I am new to using React. I have successfully rendered elements with createElement, but encountered an error when attempting to render the following JSX code, which resulted in a Uncaught SyntaxError: Unexpected token < issue: const { createElement } ...

Having trouble setting up custom breakpoints in the theme

How can I retrieve my customized breakpoint values from within the createMuiTheme? I attempted the following approach, but it seems like the breakpoint values are still set to the default value. import { createMuiTheme } from '@material-ui/core/styles ...

The functionality for bold and italics does not seem to be functioning properly in either Firefox

Text formatted with <b></b> and <i></i> tags appears correctly on iPhone and Internet Explorer, but lacks formatting in Firefox or Chrome. I have included the .css files below. Additionally, I attempted to add i { font-style:italic ...

What are some strategies to stop a jQuery UI button created with a link from inheriting the link's text color?

I recently came across a recommendation to create a jQuery button on top of a link for redirect purposes: <a href="/search" class="button">My link</> $(".button").button(); However, I noticed that if the button class has a red foreground colo ...

Error encountered: The function store.getState is not defined in the Next.js application

I encountered an issue while creating a redux store in my Next.js and React.js app. The error message "Uncaught TypeError: store.getState is not a function" appears when I try to access the store without using a provider. Can someone assist me with resolvi ...

No data being displayed or returned from API when using async await

My Ionic 6 + Angular 14 application is currently facing an issue with displaying data retrieved from an API... I have implemented a service to fetch the data from the API and then called this service in the component. The app compiles without any errors a ...

Is there a way to use JavaScript to switch the entire div on and off

I have a function called done that I want to use to toggle the visibility of my "temp" division. tasks.innerHTML += `<div id="temp"> <span id="taskname"> ${input.value} </span> <button class="d ...

Experience the smooth CSS3 transition effects on iOS devices such as iPhones and iPads. Elevate the appearance of DOM objects with

I have a basic image contained within a div tag. I use JavaScript to add a transition effect to the div element: <div style="transition: opacity 0.8s linear; opacity: 0.5;"><img src="..." /></div> At the end of the transition duration ...

What is the best location to store a Variable in React in order to access it throughout my entire application?

Hey everyone, I'm currently working on some updates for a React app as a beginner. I have a query regarding a const named Users List which looks like this: "u_469": { "ID": "469", "UID": " ...

Using React to iterate over an array of objects and generate Date TextFields in Material UI

I have an array of objects representing different stages in a specific process, each stage identified by an id and name. The structure of the array is as follows: const stages = [ { id: 1, name: initialize }, { id: 2, name: execute ...