zOthix
zOthix

Reputation: 556

Material ui AppBar text color change to white / back functionality

How does material ui AppBar change text color to white / black color depending on if AppBar color is dark or light is there a function that i can use from material ui? i checked their document and couldn't find function myself i have tried css

<style>
.container {
  background-color: #ff0001;
  padding: 15px;
}

.container p {
  mix-blend-mode: difference;
  color: white
}
</style>



<div class="container">
  <p> asd </p>
</div>

But it doesnt give only white / black color

Upvotes: 2

Views: 1711

Answers (1)

kausko
kausko

Reputation: 988

Material UI has built-in support for easily switching between light and dark modes. All you need to do is build theme objects for both modes, wrap your code with a ThemeProvider, and use state (and context) to toggle between light and dark mode. Reference links:

  1. ThemeProvider
  2. Theme object. Here, you can set the palette.type property as light or dark as per your convenience.

Correction:

Material-UI uses the main color in palette.primary/secondary as an input to get the ideal contrasting text color. This works for all MUI components (like AppBar). The exact source code is available here, in the getContrastText function. They have also linked sources in the code that use scss to achieve the same.

I didn't fully understand the logic behind this implementation, but I hope the linked code answers your question.

Edit 2:

The getContrastText can be used with the theme object in the following manner:

const useStyles = makeStyles(theme => ({
  "key": {
    "color": theme.palette.getContrastText("#cfe8fc") // returns rgba(0,0,0,0.87)
  }
})

This theme object can also be obtained using the useTheme hook or the withStyles HOC.

Upvotes: 4

Related Questions