I am trying to provide overrides in the theme for buttons that are contained, primary and hovered. I tried this but it doesn't work
CODESANDBOX LINK CLICK HERE
theme/overrides/MuiButton.js
import palette from '../palette';
export default {
contained: {
backgroundColor: '#FFFFFF',
'&.primary': {
'&:hover': {
backgroundColor: palette.primary.dark,
},
},
},
};
theme/overrides/index.js
import MuiButton from "./MuiButton";
export default {
MuiButton
};
theme/index.js
import { createMuiTheme } from "#material-ui/core";
import palette from "./palette";
import typography from "./typography";
import overrides from "./overrides";
const theme = createMuiTheme({
palette,
typography,
overrides,
zIndex: {
appBar: 1200,
drawer: 1100
}
});
export default theme;
The best resource for determining how to appropriately override the default styles in your theme, is to look at how the default styles are defined.
From https://github.com/mui-org/material-ui/blob/v4.11.0/packages/material-ui/src/Button/Button.js#L138:
containedPrimary: {
color: theme.palette.primary.contrastText,
backgroundColor: theme.palette.primary.main,
'&:hover': {
backgroundColor: theme.palette.primary.dark,
// Reset on touch devices, it doesn't add specificity
'#media (hover: none)': {
backgroundColor: theme.palette.primary.main,
},
},
},
Translating this approach to the code in your question would look like this:
import palette from '../palette';
export default {
containedPrimary: {
backgroundColor: '#FFFFFF',
'&:hover': {
backgroundColor: palette.primary.dark,
},
},
};
Related
I have this simple component:
import React from "react";
import { Grid } from "#mui/material";
import clsx from "clsx";
import theme from "../../theme";
// styling
import { makeStyles } from "#mui/styles";
const useStyles = makeStyles(() => ({
buildContainers: {
"&.MuiGrid-root": {
height: "calc(calc((100vmin - 64px)",
},
},
flowchartContainer: {
"&.MuiGrid-root": {
backgroundColor: theme.palette.secondary,
},
},
}));
const BuildSection: React.FC = () => {
const classes = useStyles();
return (
<Grid container>
<Grid item className={classes.buildContainers} xs={2.8}>
Tools
</Grid>
<Grid
item
className={clsx(classes.buildContainers, classes.flowchartContainer)}
xs={12 - 2.8}>
Flowchart
</Grid>
</Grid>
);
};
export default BuildSection;
I want to change the backgroundColor to a color from my theme, but I get [object object] in the console styling sheet and the background color is not changing. What am I doing wrong? if I use the spread operator, it works for other component.
my theme:
import { createTheme } from "#mui/material/styles";
import "#mui/material/styles";
import "#mui/material/styles/createPalette";
enum themePalette {
ARCBLACK = "#181824",
ARCGREY = "#f5f5f5",
}
enum typographyFonts {
H3 = 300,
}
// adding a field
declare module "#mui/material/styles" {
interface TypographyVariants {
buttonStyleHeader: React.CSSProperties;
buttonStyleHeaderHover: React.CSSProperties;
estimateBtn: React.CSSProperties;
}
// allow configuration using `createTheme`
interface TypographyVariantsOptions {
buttonStyleHeader?: React.CSSProperties;
buttonStyleHeaderHover?: React.CSSProperties;
}
}
// Update the Typography's variant prop options
declare module "#mui/material/Typography" {
interface TypographyPropsVariantOverrides {
buttonStyleHeader: true;
buttonStyleHeaderHover: true;
}
}
declare module "#mui/material/styles/createPalette" {
interface CommonColors {
// might need more colors here3
}
}
const theme = createTheme({
palette: {
primary: {
main: themePalette.ARCBLACK,
},
secondary: {
main: themePalette.ARCGREY,
},
},
typography: {
h3: {
fontWeight: typographyFonts.H3,
},
buttonStyleHeader: {
backgroundColor: themePalette.ARCGREY,
textTransform: "capitalize",
fontSize: 19,
},
buttonStyleHeaderHover: {
backgroundColor: themePalette.ARCBLACK,
color: "white",
},
},
});
export default theme;
I know that for MUI v17+ the makeStyles have been depricated, but I don't know why the theme won't take this theme property.
I have some unexpected CSS behaviour that I don't understand - can anyone help me understand why it's happening, and help me get my CSS imports right?
I have a react app that uses a single component, that imports a stylesheet from a separate file brand.js. The component has an <Avatar className={classes.avatarTM}>; brand.js defines that class as having a backgroundColour of Dark Blue, which is what I'm expecting.
But when I load the app in Chrome, that avatar loads grey, not blue. Inspecting the element shows that two styles apply: .makeStyles-avatarTM-11 with the expected backgroundColor of primary.dark, and .MUIAvatar-colorDefault with backgroundColor #bdbdbd. colorDefault takes precedence on backgroundColor over avatarTM-11, so I get a grey avatar. This is not good.
If I then edit the // deleteme comment in brand.js in Visual Studio and save the file, React auto-refreshes the avatar in Chrome in Blue. avatarTM-11 is now taking precedence over colorDefault.
If I then reload the page in Chrome, it reloads as default grey.
But the bit that really screws up my attempts at bugfixing is that if I create a new file brand2.js, and copy/paste the exact content of brand.js into that new file, then modify the imports in App2.js and testComponent.js to import brand2 instead of brand, it works just fine. avatarTM-11 now takes precedence over default no matter what loads the page, and I get a blue avatar.
So just use brand2 instead of brand, right? Right. So I delete brand.js.... and the problem comes back.
What exactly is happening here? How do I get my defined avatarTM style to always take precedence, no matter what is loading the page or what the stylesheet is called? Why should the presence or absence of a file that is not being used by the app affect anything?
app2.js:
import React from 'react';
import { ThemeProvider } from '#material-ui/core/styles';
import { theme } from './components/Brand';
import TestComponent from './components/testComponent';
export default function App() {
return (
<React.Fragment>
<ThemeProvider theme={theme}>
<TestComponent />
</ThemeProvider>
</React.Fragment>
);
}
testComponent.js:
import React from 'react';
import Avatar from '#material-ui/core/Avatar';
import Card from '#material-ui/core/Card';
import CardHeader from '#material-ui/core/CardHeader';
import { useStyles } from './Brand';
export default function TestComponent() {
const classes = useStyles();
return (
<Card className={classes.card} variant="outlined">
<CardHeader
avatar={
<Avatar aria-label="testComponent" className={classes.avatarTM}>
t
</Avatar>
}
title="testComponent"
/>
</Card>
)}
brand.js:
import { createMuiTheme } from '#material-ui/core/styles';
import { makeStyles } from '#material-ui/core/styles';
const theme = createMuiTheme({
palette: {
primary: {
main: '#014EAA',
contrastText: '#ffffff',
},
secondary: {
main: '#0099CC',
contrastText: '#ffffff',
},
info: {
main: '#666666',
contrastText: '#ffffff',
},
error: {
main: '#FF6600',
contrastText: '#ffffff',
},
success: {
main: '#339933',
contrastText: '#ffffff',
},
},
});
// deleteme
const useStyles = makeStyles(theme => ({
root: {
color: theme.palette.primary,
fontSize: 10,
padding: '6px 12px',
fontFamily: ['sans-serif']
},
card: {
minwidth: 275,
},
title: {
fontSize: 24
},
cardTitle: {
fontSize: 24,
color: theme.palette.primary.main,
},
cardSubtitle: {
fontSize: 14,
color: theme.palette.secondary.main
},
cardDescription: {
fontSize: 10,
},
avatarTM: {
backgroundColor: theme.palette.primary.dark
},
avatarUnknown: {
backgroundColor: theme.palette.warning.main
},
avatarFixed: {
backgroundColor: theme.palette.primary.light
},
}));
export { theme, useStyles }
You can try force this style putting property like this:
avatarTM: {
backgroundColor: 'theme.palette.primary.dark !important'
},
I am trying to customize the colors in withAuthenticator HOC aws-amplifier login screen.
I followed:
https://aws-amplify.github.io/docs/js/authentication#using-components-in-react
and also read:
https://medium.com/#coryschimmoeller/customizing-the-authentication-experience-of-amplifys-withauthenticator-e6f2089ff469
import { AmplifyTheme } from 'aws-amplify-react';
const myTheme = {
...AmplifyTheme,
BackgroundColor: { color: 'blue',backgroundColor: 'blue' },
button: { color: 'blue',backgroundColor: 'blue' },
amazonSignInButton: { color: 'blue',backgroundColor: 'blue' },
signInButton: { backgroundColor: 'blue' , color: 'blue'}
};
...
//export default App;
export default withAuthenticator(App, myTheme );
amplify still renders the AWS default look and feel. I doesn't make any difference what I put in myTheme, looks like as if it is ignored completely.
Thanks for any feedback in advance.
You need to adress the different elements like so:
import { AmplifyTheme } from "aws-amplify-react";
const authTheme = {
...AmplifyTheme,
sectionHeader:{
...AmplifyTheme.sectionHeader,
color:"red",
},
formSection: {
...AmplifyTheme.formSection,
backgroundColor: "green",
},
sectionFooter: {
...AmplifyTheme.sectionFooter,
backgroundColor: "purple"
},
button: {
...AmplifyTheme.button,
backgroundColor: "blue"
}
}
export default withAuthenticator(App, { theme: authTheme });
If you are not sure about the names of the different elements you can look them up in the developer console of your browser. It´s a bit tedious but i haven´t found a documentation so far
Taken from the documentation:
Web
const MyTheme = {
signInButtonIcon: { 'display': 'none' },
googleSignInButton: { 'backgroundColor': 'red', 'borderColor': 'red' }
}
<Authenticator theme={MyTheme} />
Web components reference
React Native
import { AmplifyTheme } from 'aws-amplify-react-native';
const MySectionHeader = Object.assign({}, AmplifyTheme.sectionHeader, { background: 'orange' });
const MyTheme = Object.assign({}, AmplifyTheme, { sectionHeader: MySectionHeader });
<Authenticator theme={MyTheme} />
React Native components reference
Since the question is about withAuthenticator specifically, the previous examples apply to that too:
export default withAuthenticator(App, false, [], null, MyTheme);
I have ReactJS project and I want to change colour of button during clicking. I know that it is a Ripple API but it's very incomprehensible to use it. Could someone advise me how can I do that?
I've tried to create two elements - parent and child - and changed background of child to transparent while clicking. Unfortunately I have also 'classes' object responsible for changing class if button is active and it is just not working.
My code below:
import React, { Component } from 'react';
import { withStyles } from '#material-ui/core/styles';
import Button from '#material-ui/core/Button';
import PropTypes from 'prop-types';
import styles from './MydButton.style';
class MyButton extends Component {
constructor(props) {
super(props);
this.state = {
isClicked: false
};
}
handleClick = () => {
this.setState({ isClicked: !this.state.isClicked });
}
render() {
const {
classes,
children,
color,
disabled,
className,
onClick,
type,
border,
...props
} = this.props;
const myClass = this.state.isClicked ? 'auxClass' : 'buttonDefaultRoot';
return (
<div className={classes.parentRoot} >
<Button
classes={{
root: disabled
? classes.buttonDisabledRoot
: classes.buttonRoot,
label: disabled
? classes.buttonLabelDisabled
: classes.buttonLabel,
}}
{...props}
onClick={this.handleClick}
className={myClass}
disabled={disabled}
type={type === undefined ? 'button' : type}
>
{children}
</Button>
</div>
)
}
};
MyButton.propTypes = {
children: PropTypes.string.isRequired,
disabled: PropTypes.bool,
classes: PropTypes.object.isRequired,
};
MyButton.defaultProps = {
disabled: false,
};
export default withStyles(styles)(MyButton);
and styles:
const buttonRoot = {
border: 0,
height: 48,
width: '100%',
}
export default theme => ({
buttonDefaultRoot: {
...buttonRoot,
transition: 'all 1s ease-in-out',
backgroundImage: 'linear-gradient(to right, #F59C81, #E65DA2, #E65DA2, #B13A97, #881E8E)',
boxShadow: '0px 1px 3px rgba(0, 0, 0, 0.16)',
backgroundSize: '300% 100%',
marginTop: 0,
'&:hover': {
backgroundPosition: '100% 0%',
transition: 'all 1s ease-in-out',
}
},
parentRoot: {
...buttonRoot,
backgroundColor: 'red',
backgroundSize: '300% 100%',
marginTop: 36,
},
auxClass: {
backgroundImage: 'none',
},
Material UI Core for ReactJS
The documentation is very good. I have updated my answer to accomodate the specific needs of this question. I have also included two general solutions for anyone who stumbles upon this question.
Tailored Solution:
Changes background color of button from classes.buttonDefaultRoot (a color defined by owner of question) to the gradient defined by the owner of this question.
First step, have a variable stored in state. You can call it whatever you want, but I'm calling bgButton. Set this to this.props.classes.buttonDefaultRoot like so:
state = {
bgButton: this.props.classes.buttonDefaultRoot,
}
Next, you want to define your function that will handle the click. Again, call it what you want. I will call it handleClick.
handleClick = () => {
const { classes } = this.props; //this grabs your css style theme
this.setState({ bgButton: classes.parentRoot.auxClass }); //accessing styles
};
A couple of things are happening here. First, I am destructuring props. So, I am creating a new const variable called classes that has the same value as this.props.classes. The classes contains a set of objects that defines your css styles for your buttons, margins, etc. You can access those styles just like you would if you were trying to get the value of a prop in an obj.
In this case you can access your button style by doing, classes.buttonDefaultRoot. That takes care of your handle click function.
Last step: render the button. In your render method you want to grab your bgButton from state like so:
render() {
const { bgButton } = this.state;
Then you want to assign your className of your button to bgButton and add the onClick functionality like this (this follows the Material UI Core documentation):
<Button variant="contained" color="primary" className={classNames(bgButton)} onClick={this.handleClick}>Button Name</Button>
Putting it all together you get this:
import React, { Component } from "react";
import Button from "#material-ui/core/Button";
import PropTypes from "prop-types";
import classNames from "classnames";
import { withStyles } from "#material-ui/core/styles";
export default theme => ({ ... }) //not going to copy all of this
class MyButton extends Component {
state = {
bgButton: null
};
handleClick = () => {
const { classes } = this.props;
this.setState({ bgButton: classes.parentRoot.auxClass });
};
render() {
const { bgButton } = this.state;
return (
<div className={classes.container}>
<Button
variant="contained"
color="primary"
className={classNames(bgButton)}
onClick={this.handleClick}
>
Custom CSS
</Button>
</div>
);
}
}
MyButton.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(MyButton);
General Solution
This solution is for those who want to use the predefined colors, i.e. default, primary, secondary, inherit. This implementation does not need the PropTypes or className imports. This will change the color from the predefined blue to the predefined pink. That's it.
state = {
bgButton: "primary",
}
handleClick = () => {
this.setState({ bgButton: "secondary" });
}
render() {
const { bgButton } = this.state;
return(
...
<Button
onClick = {this.handleClick}
variant = "contained" //checked Material UI documentation
color={bgButton}
> ..etc.
General Solution 2
To accommodate your custom styles to the button, you would have to import PropTypes and classNames and take a similar approach as the tailored solution above. The only difference here will be my syntax and class name. I am closely following the documentation here so you can easily follow along and readjust where necessary.
import React, { Component } from "react";
import Button from "#material-ui/core/Button";
import PropTypes from "prop-types";
import classNames from "classnames";
import { withStyles } from "#material-ui/core/styles";
import purple from "#material-ui/core/colors/purple";
const styles = theme => ({
container: {
display: "flex",
flexWrap: "wrap"
},
margin: {
margin: theme.spacing.unit
},
cssRoot: {
color: theme.palette.getContrastText(purple[500]),
backgroundColor: purple[500],
"&:hover": {
backgroundColor: purple[700]
}
},
bootstrapRoot: {
boxShadow: "none",
textTransform: "none",
fontSize: 16,
padding: "6px 12px",
border: "1px solid",
backgroundColor: "#007bff",
borderColor: "#007bff",
fontFamily: [
"-apple-system",
"BlinkMacSystemFont",
'"Segoe UI"',
"Roboto",
'"Helvetica Neue"',
"Arial",
"sans-serif",
'"Apple Color Emoji"',
'"Segoe UI Emoji"',
'"Segoe UI Symbol"'
].join(","),
"&:hover": {
backgroundColor: "#0069d9",
borderColor: "#0062cc"
},
"&:active": {
boxShadow: "none",
backgroundColor: "#0062cc",
borderColor: "#005cbf"
},
"&:focus": {
boxShadow: "0 0 0 0.2rem rgba(0,123,255,.5)"
}
}
});
class MyButton extends Component {
state = {
bgButton: null
};
handleClick = () => {
const { classes } = this.props;
this.setState({ bgButton: classes.cssRoot });
};
render() {
const { classes } = this.props; //this gives you access to all styles defined above, so in your className prop for your HTML tags you can put classes.container, classes.margin, classes.cssRoot, or classes.bootstrapRoot in this example.
const { bgButton } = this.state;
return (
<div className={classes.container}>
<Button
variant="contained"
color="primary"
className={classNames(bgButton)}
onClick={this.handleClick}
>
Custom CSS
</Button>
</div>
);
}
}
MyButton.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(MyButton);
A tip. You no longer need a constructor or to bind methods.
Hope this helps.
I am using React with TypeScript and Material UI. So I have the the following layout
<MuiThemeProvider theme={muiTheme}>
<My Component/>
</MuiThemeProvider>
And then in my component I have something similar to
let styles: any = ({ palette }: any) => ({
root: {
marginTop: 10
}
});
export default withStyles(styles)(MyComponent);
What would be the preferred way to go if I want to share the root class among multiple components? Can I extend Material UI theme when I am creating it using createMuiTheme?
Any advise will be highly appreciated
Here is how I define my custom theme in Material-ui
const Theme = createMuiTheme({
typography: {
fontSize: 18,
},
palette: {
primary: {
light: '#40bbbf',
main: '#032B43',
dark: '#0b777b',
},
},
customCommonClass: {
textAlign: center,
},
})
Theme.overrides = {
MuiListItemIcon: {
root: {
marginRight: 0,
},
},
MuiListItem: {
dense: {
paddingTop: '4px',
paddingBottom: '4px',
},
},
}
There are 3 parts within this creation:
the first I will define some defaults of my theme (for the fontSize, and palette color as an example)
The second I create some global class customCommonClass that I can use in all styled components down the road (your question)
I override some class of the material ui components.
hope this can help