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

What is the solution to making text appear on the top rather than on the side?

Seeking a way to keep the text description above the textbox within a definition list, however currently the text appears to the left of the box. Here is the provided HTML structure: <dl> <dt> <label>Phone Number</label> &l ...

Encountered the error message "Router.js file throwing a TypeError: next is not a function" while implementing navigation guards in my Vue 3 project

I'm puzzled as to why 'i' doesn't recognize the next function, even though I followed a similar video that implemented it without any errors. import Dashboard from "./Pages/Dashboard.vue"; import Customers from "./Pages/Customers.vue"; ...

Generate a new entry by analyzing components from a separate array in a single line

I have a list of essential items and I aim to generate a record based on the elements within that list. Each item in the required list will correspond to an empty array in the exist record. Essentially, I am looking to condense the following code into one ...

Is there a way to launch a React app directly to a specific page?

I am currently working with a router that looks like this: <React.Fragment> <Switch> <Route exact path="/page1" component={Page1} /> <PrivateRoute path="/page2" component={Page2} /> <PrivateRoute path="/p ...

Fixing the "Package Manager Not Found" Issue when Deploying a Next.js Project on Vercel

Having created a website using Next.js and aiming to deploy it on Vercel, I encountered an error during the deployment process despite meticulously following the configuration steps. The error message displayed was: "Unable to determine package manage ...

Unpacking jQuery's fancybox collection

Can anyone guide me to where I can locate the unpacked version of Jquery.fancybox-x.x.x.pack? I attempted to fix the code formatting manually in order to comprehend it better, but I'm still finding it challenging... ...

"Creating Eye-Catching CSS Animation Effects with Dynamic Initial States

I am looking to understand how I can seamlessly transition from a hover-triggered animation to an exit-hover animation, regardless of where the hover animation is in progress. Currently, if I exit hover too quickly, the animation jumps back to its starting ...

Chosen customisation for autocomplete feature

I'm currently incorporating Material UI Autocomplete into my project. Here is the code I am using: <AsyncAutocomplete field={form.$("partnerId")} fullWidth fetchOptions={store.getPartners} getOptionLabel={( ...

ReactJS Tutorial: Simple Guide to Updating Array State Data

const [rowData, setRowData] = useState([]); const old = {id: 'stud1', name: 'jake', room: '2'}; const newData = {name: 'jake', room: '3A'}; useEffect(() => { let ignore = false; ...

Share JSON data across functions by calling a function

I am currently working on a project where I need to load JSON using a JavaScript function and then make the loaded JSON objects accessible to other functions in the same namespace. However, I have encountered some difficulties in achieving this. Even after ...

Laravel Mix causes errors when running `npm run dev` and breaks the package

My nodejs package is built using ES6 features such as 'let', the spread operator (...) and default values for function arguments. However, when I run npm run production with Laravel Mix, an error message appears: ERROR Failed to compile with ...

The terser-webpack-plugin and uglifyjs-webpack-plugin are both powerful tools for optimizing

WebPack 4 now utilizes the terser-webpack-plugin in production mode or when the -p argument is specified, which essentially means including --optimize-minimize --define process.env.NODE_ENV="production". This plugin is responsible for minimizing ...

Obtain the response header variable within a Shiny application

In Apache, the LDAP login is passed to a variable called X-Remote-User in the header: I am unsure how to retrieve this information in my Shiny app. Does anyone have any ideas? Maybe using JavaScript could be a solution? ...

Encountered an error while trying to retrieve data from

Having trouble with file uploads to the S3 bucket using @aws-sdk/client-s3 library and encountering errors when uploading files larger than 70kbps: `TypeError: Failed to fetch at FetchHttpHandler.handle (fetch-http-handler.js:56:13) at PutObjectCommand ...

Variations in key-codes between Android Nexus and Samsung mobile devices

As I work on developing a "Pin Code Entry" functionality for an Ionic app, I encounter challenges with different key-codes on various Android devices. The goal is to create a login feature where users input digits into 5 fields using a Numeric keyboard. Th ...

Tips for creating a unified user interface framework for various web applications sharing a consistent design

Struggling to create a user interface framework for multiple web applications, I'm faced with the challenge of setting up the infrastructure in our unique situation: We have 7 (or more) different web applications built using asp.net mvc Some of thes ...

Position the table footer on the right side of the page

I am trying to format a table with footer items in HTML. I want the first footer item to be aligned left and the rest to be aligned right. Here is the desired layout: https://i.sstatic.net/ZRNEp.png table { width: 100% } <table class="price-list" ...

CSS ISSUE: Issue with hidden overflow causing white space next to border in nested divs

When working with a div inside another div and setting overflow to hidden, you may notice a whitespace issue around the border when zooming in and out on Chrome. Firefox handles this situation better, showing white space only in the corners of the border. ...

Helping React and MUI components become mobile responsive - Seeking guidance to make it happen

My React component uses Material-UI (MUI) and I'm working on making it mobile responsive. Here's how it looks currently: But this is the look I want to achieve: Below is the code snippet for the component: import React from 'react'; i ...

Tips for directing the scroll according to the current selection class

I am attempting to focus the scroll based on the selected class when clicking on the previous and next buttons. How can I achieve this functionality? Please review my code on https://jsfiddle.net/kannankds/bcszkqLu/ <ul class="kds"> <li>tile ...