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'
}
})
);
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 */
}
}
})
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With