Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the theme palette from within a component?

Tags:

material-ui

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?

like image 905
Fabian Avatar asked Jul 20 '18 03:07

Fabian


2 Answers

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

like image 96
Luke Peavey Avatar answered Sep 18 '22 22:09

Luke Peavey


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

like image 40
Jack Avatar answered Sep 21 '22 22:09

Jack