What is the correct way to customize colors for specific components in Material-ui?

Struggling with theming in Material-UI, particularly when it comes to customizing element colors. Some elements default to 'theme.palette.main.dark' and I want to override this behavior.

For example, the TextField and SpeedDial components automatically inherit the dark property from the theme. Removing the dark property results in a black TextField with unreadable text inside.

My current theme configuration:

import {createMuiTheme} from "@material-ui/core";
import {green, indigo, red} from "@material-ui/core/colors";

const theme = createMuiTheme({
  palette: {
    primary: {
      main: indigo.A200,
      dark: green.A100
    },
    white: {
      text: '#fff',
    },
    secondary: {
      main: red.A100,
      dark: green.A100,
    }
  }
});

export default theme;

Expectation is for the TextField and SpeedDial components to use the primary color, but they default to the dark property instead. It seems like this default behavior aims to ensure visibility, but I want full control over the colors. Struggling to find documentation on how to customize the underline and floating label colors in the TextField component.

https://codesandbox.io/s/material-demo-o52c8

Answer №1

Here is a sample code snippet demonstrating the use of vibrant colors on different parts of the TextField component.

import React from "react";
import ReactDOM from "react-dom";

import TextField from "@material-ui/core/TextField";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  root: {
    color: "white",
    backgroundColor: "fuchsia",
    "&.Mui-focused": {
      color: "orange",
      backgroundColor: "pink"
    },
    "&:before": {
      borderBottomColor: "blue"
    },
    "&:hover:not(.Mui-focused):before": {
      borderBottomColor: "green"
    },
    "&:after": {
      // focused
      borderBottomColor: "purple"
    }
  },
  input: {
    "&::selection": {
      backgroundColor: "lightgreen",
      color: "black"
    }
  }
});
const useLabelStyles = makeStyles({
  root: {
    color: "brown",
    "&.Mui-focused": {
      color: "aqua"
    }
  }
});
function App() {
  const classes = useStyles();
  const labelClasses = useLabelStyles();
  return (
    <div className="App">
      <TextField
        InputProps={{ classes: classes }}
        InputLabelProps={{ classes: labelClasses }}
        label="label"
        defaultValue="text"
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

https://codesandbox.io/s/textfield-colors-rewck?fontsize=14

Let's achieve the same appearance by utilizing the theme:

import React from "react";
import ReactDOM from "react-dom";

import TextField from "@material-ui/core/TextField";
import { createMuiTheme, ThemeProvider } from "@material-ui/core/styles";

const theme = createMuiTheme({
  overrides: {
    MuiInput: {
      root: {
        color: "white",
        backgroundColor: "fuchsia",
        "&.Mui-focused": {
          color: "orange",
          backgroundColor: "pink"
        },
        "&:before": {
          borderBottomColor: "blue"
        },
        "&:hover:not(.Mui-focused):before": {
          borderBottomColor: "green"
        },
        "&:after": {
          // focused
          borderBottomColor: "purple"
        }
      },
      input: {
        "&::selection": {
          backgroundColor: "lightgreen",
          color: "black"
        }
      }
    },
    MuiInputLabel: {
      root: {
        color: "brown",
        "&.Mui-focused": {
          color: "aqua"
        }
      }
    }
  }
});

function App() {
  return (
    <ThemeProvider theme={theme}>
      <div className="App">
        <TextField label="label" defaultValue="text" />
      </div>
    </ThemeProvider>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

https://codesandbox.io/s/textfield-colors-via-theme-09jk1?fontsize=14&hidenavigation=1&theme=dark

Check out these related answers:

  • How do I custom style the underline of Material-UI without using theme?
  • How can I change the label size of a material ui TextField?
  • Change InputLabel color of a Select component when clicked/focused
  • Change outline for OutlinedInput with React material-ui

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

Label text will not be wrapped in front of the label (bootstrap)

I'm struggling with some css coding. I want the text to wrap so the label is positioned on the middle right of the box, similar to this example: . However, currently it looks like this: http://jsfiddle.net/yuvemL1z/ and the label ends up being pushed ...

What are some strategies for maximizing the value of the initial click?

For the past few days, I've been struggling with this particular aspect of the project. Despite extensive research, I haven't been able to find a solution. The issue lies in retrieving a variable from the contextAPI. Although it updates to the co ...

Unable to scroll when utilizing ng-html-bind functionality

My device specifications: $ ionic info Your system details: Cordova CLI: 6.2.0 Gulp version: CLI version 3.9.1 Gulp local: Ionic Framework Version: 1.2.4 Ionic CLI Version: 2.0.0 Ionic App Lib Version: 2.0.0-beta.20 OS: Distributor ID: LinuxMint Desc ...

Issue with parsing JSONP using jQuery's AJAX request

I am encountering an issue with a jQuery ajax request that I have set up. Here is the code: jQuery.ajax({ url: serverAddress+'php/product.php', type: 'GET', jsonpCallback: "callback7", dataType: 'jsonp', d ...

Exploring the Variance between 'npm run serve' and 'npm run dev' Commands in Vue.js Development

Can you explain to me the distinction between npm run serve and npm run dev in vuejs? Additionally, can you clarify why it is recommended to use the npm run serve command when running a project? ...

Invoke a handler from one function within another function

I am unsure of the best approach for achieving this, or if it is even feasible, but I have two components: a main navigation bar (NavBar) that spans across the top of the page, and a sidebar drawer. NavBar: export default function NavBar() { const c ...

Using Higher Order Components (HOC) in combination with Redux compose and Typescript

I am trying to leverage two Higher Order Components (HOC) with Redux compose, but the compiler is not generating the correct types. The Compose function is defined in the Redux source code here source code. To better understand how the code works, you ca ...

What is the method for modifying the text color of P tags within a div element?

I'm having trouble changing the text color of the P tags in the card-header section for some reason dashboard.html <div class="container"> <div class="card"> <div class="card-header"> <p& ...

Is the item positioned above another item instead of being positioned to the left of it?

Looking for help with my mobile navigation setup. I want to add text that says ' ...

What steps can I take to refactor a portion of the component using React hooks?

I am trying to rewrite the life cycle methods in hooks but I am facing some issues. It seems like the component is not behaving as expected. How can I correct this? Can you provide guidance on how to properly rewrite it? useEffect(() => { updateUs ...

Grid of pictures resembling a masonry pattern

As I ponder this intricate dilemma, I am convinced that there must be a simple solution or alternative approach to finding the answer. My goal is to create a grid of random images without any gaps between them. I have an array of images that I want to dis ...

Capture the onclick attribute with jQuery and then reapply it

I am facing a challenge with a page that has several calendars composed of HTML tables where each day is represented by a td. The td elements have an onClick attribute which I need to manipulate using jQuery. Specifically, I need to remove the onClick attr ...

How to Customize the Style of Material UI's Tooltip

Is there a way to customize the background color and text color of Material UI's Tooltip? I have attempted to do so using the code snippet below without success. import { createMuiTheme } from '@material-ui/core/styles'; export const theme ...

Connecting two fields with a line on click in AngularJS

In the top section, there are 10 fields and in the bottom section, there are another 10 fields. I want to be able to connect two fields with a line when they are clicked (one from the top section and one from the bottom section). This connection should app ...

Create a recursive CSS style for an angular template and its container

I am struggling with styling CSS inside an ng-container that is used in a tree recursive call to display a tree hierarchy. <ul> <ng-template #recursiveList let-list> <li *ngFor="let item of list" [selected]="isSelected"> <sp ...

Implementing Axios interceptor is a common practice in Vue.js applications to central

Hello everyone, I'm facing a problem with the interceptor in VueJS. I can't seem to figure out where the issue lies and it's driving me crazy... I've gone through various tutorials and read numerous posts on stackoverflow, but everythi ...

Encountering a challenge while attempting to adjust the navigation bar at the top as the user scrolls through the page

I've been working on making the navigation bar stay fixed at the top of the page when the user scrolls, but I'm running into some issues. It seems that certain elements are overlapping the navigation bar, causing them to hide the navigation bar a ...

Having trouble retrieving the default selected value using the index in Angular Material's mat-button-toggle functionality

I'm encountering an issue with setting the default value for a toggle button group. The code is simple and the toggle buttons are correctly fetching values from the index, but I can't seem to get one of them to be default selected. I tried settin ...

Can you explain the role of the next() function in middleware/routes following the app.use(express.static(...)) in Express

When dealing with serving static assets generated from React source code using npm run build, the following method can be used: app.use('/', express.static(path.join(__dirname, 'apps', 'home', 'build'))) To protect ...

The Ajax POST functionality appears to be malfunctioning, whereas the PHP equivalent is operating without any

Need assistance in developing a JavaScript mobile app that will POST an authentication token to a Microsoft website. Attempting to use online JavaScript code found, but encountering failures. The JavaScript code outputs a message "GET undefined/proxy/htt ...