Changing the Input Label Color on Hover in Material-UI TextField

I have a custom styled Mui TextField called CustomTextField. It changes the input background color and font color on hover, but I also want to change the label font color when hovered over. Currently, the input background changes from black to white on hover, with the font color doing the opposite. My goal is to make the label color change from white to black when hovered over.

How can I achieve this? I attempted to add an OnMouseOver and OnMouseLeave event listener and manually set the label color, but adding the OnMouseOver listener seems to break the TextField completely. Here is my current code:

View CodeSandbox Example

const CustomTextField = styled((props) => (
    <TextField
      InputLabelProps={{
        // getTextColor() checks a state variable called hoveredControl which stores
        // the id of the currently hovered component. If the hoveredControl is this input,
        // set the text color to black, otherwise set it to white.
        sx: { color: getTextColor(props.id) },
      }}
      InputProps={{ disableUnderline: true }}
      {...props}
    />
  ))(({ theme }) => ({
    "& .MuiFilledInput-root": {
      overflow: "hidden",
      borderRadius: 4,
      backgroundColor: "#232323",
      color: "#FFFFFF",
      border: "1px solid",
      borderColor: "#2D3843",
      transition: theme.transitions.create(["border-color", "background-color", "box-shadow"]),
      "&:hover": {
        backgroundColor: "#bdbdbd",
        color: "#000000",
      },
      "&.Mui-focused": {
        color: "#000000",
        backgroundColor: "#bdbdbd",
        boxShadow: `${alpha(theme.palette.primary.main, 0.25)} 0 0 0 2px`,
        borderColor: theme.palette.primary.main,
      },
    },
}));

Answer №1

After experimenting, I successfully resolved this issue by applying specific CSS rules to the styled TextField component:

"& label.Mui-focused": {
  color: "#000000" // Adjust label color when input is focused
},
"&:hover label": {
  color: "#000000" // Modify label color on input hover
}

No need for complex state storage or mouse event listeners.

Here's the link to my solution: https://codesandbox.io/s/brave-dew-d472zl?file=/src/Fixed.js

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

Unexpected symbols appearing in image tag after AJAX response

I'm currently grappling with an issue related to an AJAX request I am working on (I am quite new to the world of AJAX). I have set up an API and my goal is to fetch a PNG image using an Authorization header that requires a token supplied by me (which ...

How to correct placeholder text display in the input of a Material UI text field

Currently, I am utilizing the material ui text field component. The issue at hand is that when the text field is in focus, the placeholder shifts to the top of the field. https://i.stack.imgur.com/P5flf.png I prefer for the placeholder to remain within ...

absence of a scrollbar on smaller window display

My website is experiencing an issue: everything displays properly when the window size matches or exceeds the background image, but on a smaller window, there is no scroll bar which causes the footer to disappear. Here is an image showing what happens wit ...

Resolve the issue with automatically generating SCSS type definitions (style.d.ts) for Preact within a TypeScript webpack setup

Utilizing webpack with Preact 10.x (nearly identical to React) and TypeScript in the VSCode environment. Following an update from Node version 12 to version 14, there seems to be a problem where *.scss files no longer automatically generate their correspo ...

Tips for validating and retrieving data from a radio button paired with an input box in reactjs

I'm diving into the world of React and facing a challenge with multiple radio buttons that have associated input fields, like in this image: https://i.stack.imgur.com/Upy3T.png Here's what I need: If a user checks a radio button with a ...

Dealing with the issue of needing to include "%20" in the URL after receiving a NextJS build

Currently, I am working on a simple NextJS (v13) project utilizing TheMoviedb API. I am fetching images and titles of content with an API request in this project. The image paths can be accessed using a variable named dt, which corresponds to either backdr ...

Can you show me how to recreate a 502 gateway timeout error?

Looking for suggestions on how to create a page that exceeds 600 seconds to load? Any tips on triggering a 502 gateway timeout error would be helpful as well. ...

Is it possible to generate multiple modal windows with similar designs but varying content?

I am facing a challenge with 140 link items that are supposed to trigger a modal window displaying a user profile for each link. The issue is that each user profile contains unique elements such as three images, a profile picture, text paragraph, and socia ...

What is the best way to include a class in an element once the scroll surpasses a certain value?

Can anyone help me understand why my attempt to assign a class to an element based on scrolling behavior is failing? The code snippet in question is: className={`arrowup ${window.pageYOffset >= 2 ? "showscroll":null}`} ...

Instructions on how to navigate to a class page by clicking a button in a ReactJS interface

I am currently working with React and have implemented 3 classes in separate files. The App.js file contains a navbar and button, which when clicked, displays a table from 'Table.js'. I have also added buttons in front of each row in the table th ...

What is the best way to access a variable from script A within script B using TypeScript?

I am looking to extract a variable from another script in order to generate the subsequent section of the page based on this data. Below is the code snippet that retrieves data from an API: import Axios from "axios"; import React from "reac ...

Encountering an error during the process of adding dependencies through yarn install

When attempting to set up material-ui locally with yarn install, I encountered an issue where the node modules were not being created. Instead, I received a series of error messages: │ @mui/monorepo: The override for '/@babel/core' includes a ...

Encountering an issue with npm installation following a recent node version upgrade

Having trouble installing Sass on Node version v16.14.0. I keep receiving this error message: https://i.stack.imgur.com/6KNcF.png ...

Could there be an issue with my website's bootstrap where badges are not being applied properly?

Currently, I am in the process of learning ReactJS and running into an issue where my bootstrap is not working within my .jsx file. Despite following a tutorial (MOSH) diligently and extensively researching on stack overflow, I have not been able to find a ...

The static files are being received by Django but are not functioning properly

I've been working on a project using django 1.7, and below is my settings.py configuration: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "assets"), ) STATIC_ROOT = "absolute/path/to/static" In the 'assets&apo ...

My Javascript file is not being recognized by MVC

Initially, I created an MVC application without fully understanding that MVC is more backend-oriented than frontend-focused. I ended up building a simple website with just HTML, CSS, and Javascript files, which worked perfectly. However, when I tried to in ...

Why isn't the HTML template opening in Outlook 7?

Does anyone know how to fix the code issue on Outlook 7? I've only included the header section of my code here, but please let me know if you need more information. I would appreciate any help with this problem. Thanks! ...

What is the trick to shortening paragraphs with dots...?

There is a p tag, <p> most iconic character in cinema</p> I need to truncate the text after 8 characters, and display dots afterwards. For example: most ic... Is there a way to achieve this using CSS? Any help with AngularJS would also be ...

Top method for passing props from child to parent React component

I am facing a challenge with passing data from child to parent components in React. I have an array that I need to save in my database, and I have set up a Parent component (AuthenticationPage.js) and a Child component (SignupForm.js) for this purpose. The ...

When passing the value of "undefined" into a function, keep in mind that the function must be declared in a separate JavaScript file. This

I'm facing an issue with my JavaScript code. I have a file named test.js that contains a function like this: export const a = (data) => { console.log(data) } In addition, I have a functional component called File.js as shown below: import Reac ...