Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Button does not change its color after Material UI theme changed

I wanted to see my contained primary button's color was slightly changed whenever the theme was changed, but I couldn't.

I saw it worked if I changed the button from the contained button to the text button by removing 'variant="contained"', but I really want to use the contained button

Is there any way to make it work?

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  // Because of <React.StrictMode>, <CssBaseline /> didn't work when theme was changed.
  // <React.StrictMode>
  //   <App/>
  // </React.StrictMode>,
  <App />,
  document.getElementById('root')
);

App.js

import React, { useState } from 'react';
import './App.css';
import { Button, Container } from '@material-ui/core';
import ChangeTheme from './components/ChangeTheme';
import { lightTheme, darkTheme } from './libs/Theme';
import { MuiThemeProvider, CssBaseline} from '@material-ui/core';


function App() {
  const [theme, setTheme] = useState(darkTheme);

  const handleChangeTheme = (setDark) => {
    setDark === true ? setTheme(darkTheme) : setTheme(lightTheme);
  }

  return (
    <MuiThemeProvider theme={theme}>
      <CssBaseline />
      <Button variant="contained" color="primary">Hi</Button>
    </MuiThemeProvider>
  );
}

export default App;

libs/Theme.js

import { createMuiTheme, responsiveFontSizes } from '@material-ui/core';

export const lightTheme = responsiveFontSizes(
  createMuiTheme({
    palette: {
      type: 'light'
    }
  })
);

export const darkTheme = responsiveFontSizes(
  createMuiTheme({
    palette: {
      type: 'dark'
    }
  })
);
like image 427
Jason KIM Avatar asked Sep 01 '25 20:09

Jason KIM


1 Answers

This is because the auto-generated dark theme provided by Material UI only changes specific colors from the palette. It does not change the primary/secondary background (the primary.main or secondary.main) colors.

Check this page out from their website, which lists the colors that are changed by the auto-generated dark theme. You will find there that text color is among the colors that are changed on theme change; that explains why you could see the change in your variant="text" button but not in the variant="contained" one.

Your best bet is to specify the changed colors manually for the dark theme in your theme declaration. Something like:

export const darkTheme = responsiveFontSizes(
  createMuiTheme({
    palette: {
      type: 'dark',
      primary: {
        main: "#000000" /*or whatever color you desire */
      }
    }
  })
);
like image 186
Arjun Avatar answered Sep 05 '25 11:09

Arjun