I'm trying to build a component that renders a div
that displays an error.
function ErrorDiv(props) {
return (
<Card>
<Typography>{props.message}</Typography>
</Card>
);
}
I want to style the <Card>
such that the background color is palette.error.main
, and <Typography>
such that the font color is white.
However, I'm not sure how I can access the theme colors. Is there a palette
variable that is exposed? Or should I export individual colors as strings in my theme-creating module, and import the color for use here?
Here are links to the documentation on this
CSS in JS
Accessing the Theme in a Component
Here is an example using withStyles:
import { withStyles } from '@material-ui/core/styles'
const styles = theme => ({
card: {
background: theme.palette.error.main,
color: '#fff'
}
})
function ErrorCard({ classes }) {
return (
<div>
<Card className={classes.card}>
<Typography variant="title" color="inherit">
Something went wrong!!
</Typography>
</Card>
</div>
)
}
export default withStyles(styles)(ErrorCard)
Live example on Code Sandbox
Form the docs: Use Theme hook
import { useTheme } from '@material-ui/styles';
function DeepChild() {
const theme = useTheme();
return <span>{`spacing ${theme.spacing}`}</span>;
}
Not your typical use case but it is necessary for accessing an array of colour from the theme, for example
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