A guide to customizing the appearance of Textfield labels in Material-UI using React

Can someone assist me with changing the label color in Material-UI from grey to black? I am new to Material-UI and struggling to figure it out.

Below is the code snippet:

import React from "react";
import ReactDOM from "react-dom";
import { TextField, Button, Grid } from "@material-ui/core";

class App extends React.Component {
  render() {
    return (
      <Grid container justify={"center"} alignItems={"center"} spacing={1}>
        <Grid item>
          <TextField
            id="outlined-name"
            label="Name"
            value={"Enter value"}
            onChange={() => console.log("I was changed")}
            margin="normal"
            variant="outlined"
          />
        </Grid>
        <Grid item>
          <Button variant="contained" color="primary">
            Submit
          </Button>
        </Grid>
      </Grid>
    );
  }
}

Check out the code on "https://codesandbox.io/s/fancy-morning-30owz"

Answer №1

When utilizing the selection tools in your browser, you will discover:

The class name that is utilized is MuiFormLabel-root

<label class="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-formControl MuiInputLabel-animated MuiInputLabel-shrink MuiInputLabel-outlined MuiFormLabel-filled" data-shrink="true" for="outlined-name">Name</label>

To apply styles using a nesting selector to the TextField component

Functional component

import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles(theme => ({
  root: {
    "& .MuiFormLabel-root": {
      color: "red" // or black
    }
  }
}));
...
const classes = useStyles();

Classical component

import { withStyles, createStyles } from "@material-ui/core/styles";
const styles = theme => createStyles({
  root: {
    "& .MuiFormLabel-root": {
      color: "red"
    }
  }
});
...
const { classes } = this.props;
...
export default withStyles(styles)(App);

usage

<TextField
  className={classes.root}
  ...
>
</TextField>

This method allows you to modify the label color as displayed in the screenshot below (currently red)


https://i.sstatic.net/ZuL1n.png


Experiment with it online:

https://codesandbox.io/s/staging-framework-3h4m8?fontsize=14&hidenavigation=1&noreferrer&theme=dark

Answer №2

To keep your style in a different document, use the following code:

.CustomTextField-root > heading {
    background-color: $bg-color;
    text-color: $color;
}

.CustomTextField-root > .CustomLabel-root.Custom-focused {
    text-color: $color;
}

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

Expanding a reducer to various pages with unique data variations

On my webpage, I have a section that displays tasks related to a specific project and the corresponding actions for each task. For example, if the URL is /project/5, the layout of the page will be like this: Project 5 Title, Due Date Task #1 : Task 1 t ...

The property "state" of RouteComponentProps location does not exist in the provided type {}

We recently encountered a new error that was not present before. Previously, our code compiled without any issues and the compilation process went smoothly. However, individuals who installed the react application from scratch are now facing an error speci ...

I am attempting to integrate the file path of my images using PHP

Let me start off by showing you the file structure of my website. File Structure Of my website In order to organize my code, I created a header file named header.html.php which contains all the necessary elements for the header, including an image tag fo ...

To avoid any sudden movements on the page when adding elements to the DOM using jQuery, is there a way to prevent the page from

I have a challenge where I am moving a DIV from a hidden iFrame to the top of a page using jQuery. Here is my current code: $(document).ready(function($) { $('#precontainer').clone().insertBefore(parent.document.querySelectorAll(".maincontainer" ...

Guidance on setting up React Route 4 deployment on IIS

I'm currently working on a react application that consists of the following files and folders: ├── static │ ├── css │ │ └── someCssFile.css │ ├── js │ │ └── someJsFile.js ├── index.html ├ ...

Having trouble with CSS and javascript files not resolving after moving app to a new Windows 7 development machine

I have recently migrated my ASP.Net 3.5 web site from my old XP sp3 machine to a new Win 7 64-bit dev machine. The web application utilizes Master Pages, App_Themes with style sheets and images, as well as an image folder located off the main root. Additio ...

Can arrays be passed as function parameters in CrossRider without the need to convert them into objects first?

Our team is currently utilizing CrossRider to develop an extension specifically for Internet Explorer. We have a crucial object that is downloaded from , but we are facing an issue where arrays within this object are getting converted into objects with int ...

Exploring Vue and Nuxt JS: What Causes the Issue of Unable to Create the Property 'display' on the String 'bottom:30px;right:30px;'

this piece of code is designed for a component that allows users to jump back to the top of the page. However, after refreshing the page, it stops working and throws an error. The project uses the Nuxt and Vue framework. Can anyone identify the reason behi ...

Sample Source Code for Jssor Slider

Is there a way to replicate the slider effect shown in this example using Jssor Slider without any available sample code or source? I would greatly appreciate any assistance with achieving this. Thank you ...

php Use cURL and the DOM to extract content with specified CSS styling

Unclear in the title, I want to copy all content from a specific div on an existing webpage (not owned by me). The code successfully extracts the content. Extractor code: // Get Data $curl_handle=curl_init(); curl_setopt($c ...

The grid layout in Bootstrap 4 does not seem to be compatible with dompdf

I am in the process of using dompdf for rendering a PDF file. Our application is built on Bootstrap 4 framework, and I want to incorporate it into the twig template used for generating our documents. However, I have encountered an issue with the Bootstrap ...

Create circular Styled components in React JS

Currently, I am attempting to create a component within a wrapped styled component. The Styled component has a circular shape, and I am seeking assistance in styling it accordingly. Can anyone provide guidance on how to apply the styles needed to achieve a ...

"Enhancing user experience with dynamic input fields through Ajax auto-fill functionality

I have a unique invoice form that allows users to add multiple parts at their discretion. As the user inputs a part number, an AJAX script automatically populates the description and price fields. The script functions properly for the initial input fields ...

Swap out AJAX following a successful retrieval and when managing errors

I currently have a basic AJAX load function set up to load a specific URL: <div id="load"> <h1 id="status">Loading...</h1> </div> <script type="text/javascript"> $(document).ready(function(){ $.ajaxSetup({cache: false}); var ...

JavaScript onclick event on an image element

I have a JavaScript function that shows images using CSS styles. <script type="text/javascript"> $(function () { $("div[style]").click(function() { $("#full-wrap-new").css("background-image", $(this).css("background-image")); }); }); ...

Explore the power of accessing XML data using JavaScript

Currently, I am dealing with an XML file and attempting to extract data from it. The structure of the XML file is as follows: <doc> <str name="name">Rocky</str> <str name="Last_name">balboa</str> <str name="age ...

Store the information retrieved from an Ajax call regarding an artist on the page, ensuring that it is only saved once for that

I have been working on a single-page application that utilizes the Spotify REST API and JQuery to enable users to search for an artist and display their information on the page. However, I want to ensure that the app saves details about each artist only ...

Ways to eliminate excess space in a string using Robot Framework

My Variable : 54, 22 What I desire : 54,22 I attempted the following methods: Executing Javascript code var a = 54, 22;var x = a.split(' ').join('');return x and Executing Javascript code var a = 54, 22;var x = a.replace(/&bso ...

Stopping the interval in Vue before the component is destroyed

I am currently facing an issue with a countdown timer implemented on a component. The timer functions properly, however, I want it to stop counting down once the user navigates away from the page where the component is located. I have attempted to use cl ...

What are some ways you could utilize componentDidUpdate to make updates seamlessly without the need to manually refresh the page?

When looking at the data, the letter F represents the number of favorited movies and W indicates the number of watched movies. I have created a button that resets the count of favorited movies to 0. However, in order for this change to be reflected withou ...