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)



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

Error encountered when attempting to send a jQuery Post to API due to Access-Control-Allow-Origin issue

I've been researching the 'Access-Control-Allow-Origin' error extensively, but I am still struggling to understand what needs to be fixed. Here's the code snippet in question: $.ajax({ url: 'http://54.149.190.45:8000/image/upl ...

The directive in an Angular app is not loaded due to lazy loading

Seeking assistance with lazy loading a directive in my Angular application, I am using ui.router and oc.lazyLoad. Below is the code snippet: menu : <ul> <li><a ui-sref="home">Home</a></li> <li><a ui-sre ...

The continuous re-rendering is being triggered by the Async/Await Function

I am facing an issue with fetching data from the backend using axios. The function is returning a Promise and each time I call it, my component keeps rendering continuously. Below is the code snippet: import { useState } from "react"; import Ax ...

The ng-controller (dropdown menu) is functioning properly when tested locally and on JSFiddle, however, it is not working on

My HTML website with ng-app is functioning properly when tested locally and on certain coding platforms like JSFiddle and CodePen. However, it seems to encounter issues when deployed on Google Sites, Github, W3, and similar websites. The main functionalit ...

Is there a simple solution to show script 1 to visitors from the US and Canada, while displaying script 2 to visitors from other countries?

I'm looking for a simple script that can show one script to visitors from the US and Canada, and another script to visitors from other countries. It doesn't have to be perfect, but using a service like seems too complex for me. Is there a stra ...

A comprehensive walkthrough on getting started with your project setup using Cordova, Onsen, and React - from setting up

Are there any comprehensive step-by-step guides available for creating an Onsen UI 2 + React + Redux + Cordova application from the ground up? While there are many resources out there, very few of them cover the initial project setup process: which npm pa ...

What is the most efficient method for saving Redux state into local state using React JS?

In my application, I have a reducer called tables which includes a state named mainTables. I am utilizing the react-dnd library to manage the positioning of these tables. const initialState = { channel: null, errors: null, mainTables: [], takeaways: [ ...

Avoid cascading of the 'display' property in JavaScript styling to prevent inheritance

Is there a way in Javascript to toggle the visibility of a larger portion of HTML without affecting inner display properties with display: <value>? Despite setting an outer display property using Javascript, the inner display properties are also alt ...

Increase the font size of a div using CSS to make it appear larger

Utilizing a WYSIWYG-editor, I am creating content that I want to display with double font-size, without directly altering the HTML code. Here is an example of the HTML structure: <div id="contents"> <p style="text-align:center"> <spa ...

The React.js component search test encounters errors in locating components

I have been working on a React app that utilizes Redux and React-router. I am currently writing tests using React TestUtils, and I encountered an issue with the following test results: The first expect statement is successful: expect(nav).to.have.length(1) ...

Tips for fading an image as you scroll using CSS and JavaScript?

I have been dedicating my day to mastering the art of website development. However, I am facing a challenge that is proving to be quite difficult. I am looking to create a smooth transition effect where an image gradually blurs while scrolling down, and re ...

"Enhance user experience with AJAX for selecting multiple checkboxes or performing mult

Hey there! So, I've got a question about handling multiple checkboxes with the same name in a form. Here's an example of what I'm working with: <input type="checkbox" name="myname[]" value="1" /> <input type="checkbox" name="myname ...

Is there a way to eliminate whitespace in a pathname while using react?

I have a dropdown menu with items stored in an array called "lis". These items are mapped into the dropdown when it is open. My goal now is to use the names as both content and paths to open pages. While I have successfully achieved this, my issue lies wit ...

A conflict with the Ajax file is causing an automatic logout

In my Rails application, there is a page with a table that uses partial AJAX to increase the capacity attribute in a time entity. You can view the visual representation of the table here. By clicking the plus/minus button, the capacity attribute increases ...

The absence of the iframe in ie8 is causing problems that cannot be fixed with relative positioning

On a website, I am integrating an external 2-factor authentication solution called Duo Web using their PHP and Javascript. It works smoothly on all browsers except for IE8. When the user passes the initial login screen, the 2FA login page loads, but the if ...

React JS tutorial: deleting an entry from the browser's localStorage

I am currently working on an App that fetches data from an API and updates it randomly every 3 seconds. The user has the ability to print the data by clicking a button, which can also be used to stop the random updates. I have managed to implement this fun ...

AngularJS : "Executing successive promises" with additional functions interspersed

Recently, I encountered a challenge in my Angular project. As a newcomer to Angular, I was tasked with modifying a directive that handles forms to ensure the submit button is disabled during processing and then enabled again once all operations are complet ...

Advantages of choosing between the <NextLink/> and the <Button href="/somePage"/> components in the powerful Mui React UI libraries

Currently engaged in a project, I am wondering if there exists a substantial disparity in the utilization of these two components. Prior to this change, the return button was implemented as follows: <NextLink href="/settings" ...

Ways to pinpoint a particular division and switch its class on and off?

Consider this scenario, where a menu is presented: function toggleHiddenContent(tabClass) { let t = document.querySelectorAll(tabClass); for(var i = 0; i<t.length; i++) { t[i].classList.toggle="visible-class"; } } .hidden-conten ...

What is the best way to expand the width of a table cell in a React + Material project?

Currently, I am utilizing material UI in conjunction with React to display my data in a table format. Within the table, there are specific titles such as "GENERAL_INFORMATION" and "INFORMATION" that I intend to center align. However, I have encountered an ...