Explore a personalized color scheme within MUI themes to enhance your design

I'm looking to customize the colors in my theme for specific categories within my application.

I set up a theme and am utilizing it in my component like this:

theme.tsx

import { createTheme, Theme } from '@mui/material/styles'
import { red } from '@mui/material/colors'

export const theme: Theme = createTheme({
  palette: {
    primary: {
      main: blue[800]
    },
    secondary: {
      main: '#19857b'
    },
    cat1: {
      main: red[700]
    }
  }
})

circle.tsx

import CircleIcon from '@mui/icons-material/FiberManualRecord'
import {theme} from '/shared/theme'

export function Circle() {
  return (
    <>
    <CircleIcon style={{ color: theme.palette.cat1.main }} />
    <CircleIcon style={{ color: theme.palette.cat1[200] }} />
    </>
  )
}

My goal is to dynamically set element colors. For example, I want circles in category 1 to be red, with all necessary colors defined in the theme. Rather than importing every possible color in each component, I rely on the theme for color definitions.

Additionally, I aim to calculate the color of another element based on these definitions. As shown in the code above, I'm trying to determine the shade '200' of red.

Answer №1

Before you start styling, consider avoiding the use of styles as it can be difficult to override. MUI provides better alternatives like the sx prop and styled function, which automatically provide the theme object when used as a callback. So, update your code to:

<CircleIcon sx={{ color: theme => theme.palette.cat1.main }} />

If you need access to other color variants, such as primary or secondary, utilize the augmentColor() function to let MUI generate the dark, light, and contrastText colors for you:

import {
  createTheme,
  ThemeProvider,
  Theme,
  lighten,
  darken
} from "@mui/material/styles";

const { palette } = createTheme();
const { augmentColor } = palette;
createTheme({
  palette: {
    // Specify the main, dark, light, and contrastText variants based on red[500] for cat1
    cat1: augmentColor({ color: red }),

    // Generate variants based on only red[100] for cat2
    cat2: augmentColor({ color: { main: red[100] } })

    // Darken and lighten shades are calculated in augmentColor, but you can manually define them for cat3
    cat3: augmentColor({
      color: {
        dark: darken(red[300], 0.6),
        main: red[300],
        light: lighten(red[300], 0.6)
      }
    })
  }
})

Check out the Live Demo

https://codesandbox.io/s/69525574-use-custom-color-schema-in-mui-theme-1gzk7?file=/demo.tsx

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React JS for loop not displaying any output

I am trying to create a component that loops from 0 to the value entered as a prop. if (props.number !== "" && props.toPow !== "") { for (let i = 0; i < props.toPow; i++) { return ( <div> & ...

Knockout.js client-side validation system

Currently working on a sophisticated client-side web application and I'm in search of the perfect framework for handling validations. I experimented with JQuery validation plugin, but unfortunately it didn't integrate smoothly with knockout.js da ...

Encountered a network error during authentication in a React API call

I have encountered an error message when making an authenticated API call. Below is my code snippet where I am receiving an "Error on Authentication Error". componentDidMount() { let config = {'Authorization': 'Here i have pasted the a ...

Regularly updating a book's interactive pages with turn.js technology

I experimented with generating dynamic content in turn.js using the sample provided here. This is an excerpt of the code I have written: <body> <div id="paper"> </div> </body> <script type="text/javascript"> $(win ...

Writing xpath or cssSelector for a material-ui element can be challenging, especially when the element disappears. Here are some tips to

Here is an example of an element (textbox) with various attributes: <input aria-invalid="false" autocomplete="off" id="multiple-limit-tags" required="" type="text" class="MuiInputBase-input MuiOutli ...

Endless scrolling with redux and react

I'm facing an issue while trying to implement infinite scroll in a React-based application that utilizes Redux for state management. I am attempting to dispatch an action on page scroll but have been unsuccessful so far. Below is my code snippet: // ...

Unlocking the Potential of a Subordinate Menu

Struggling to retrieve the value of authorId using the getValues function from react-hook-form within a child component. Despite clicking on "Print Values", the value remains inaccessible. Any suggestions? Below are the snippets for the two components: co ...

Is there a way to pass a token variable from the main page to an iframe without relying on a post message?

I am seeking assistance on how to transfer a variable from a parent window to an iframe. My situation is as follows: I am working with 2 Angular5 applications named A and B . Application B is loaded within Application A using an iframe. The aut ...

Why does Vuetify/Javascript keep throwing a ReferenceError stating that the variable is undefined?

I'm currently developing in Vuetify and I want to incorporate a javascript client for Prometheus to fetch data for my application. You can find the page Here. Despite following their example, I keep encountering a ReferenceError: Prometheus is not def ...

Issue encountered in IE9 and IE10 when loading the angular library results in the "SCRIPT5007: Object expected" error for Angular JS

I am currently working on an AngularJS application that needs to be compatible with Firefox, IE 9, and IE 10. We are using the latest version of the AngularJS library (currently at 1.3.15). Our serverside is based on Java in the JavaEE platform, running on ...

Using JQuery to Update Text, Link, and Icon in a Bootstrap Button Group

I have a Bootstrap Button group with a split button dropdown. My goal is to change the text, href, and icon on the button when an option is selected from the dropdown. I am able to change the text successfully, but I'm having trouble updating the HREF ...

Dealing with functions that may not consistently return a promise

When dealing with a situation where a function does not always return a promise, how can it be best handled? The complexity of my current code prevents me from providing a detailed explanation, but essentially, the issue involves checking a condition and t ...

Performing operations on information within a map function

While using toLocaleString within this map, I encountered an issue where only one of the payment.amount's returned formatted as currency. {props.paymentDates.map((payment, index) => ( <tr key={"payment-" + index}> <td>{i ...

Using Vue to change select box data separately

I have a functional select box that is currently sending the selected value to a method when the change event occurs. However, I am wondering about something: Let's say I also want to send the cat_id value at the time of selection (to create an objec ...

method that provides route-specific variable outputs

I have a situation where multiple routes require the same userdata from the database. Although I have a function to verify if the user is logged in, this function does not return the user variables. Here is an example route: app.get('/template', ...

The React Material UI error message is indicating that a <div> element is not allowed to be nested inside a <p> element

I'm attempting to integrate a react-bootstrap carousel into each React material-UI tab. However, I encountered the error message Warning: validateDOMNesting(...): <div> cannot appear as a descendant of <p>. Can anyone advise me on where th ...

Adjust the text according to the selected checkbox option

I am attempting to update the displayed text based on whether a checkbox is currently checked or not. The value of the viewable text should reflect the user's selection. I believe I am close, but the functionality is not working as expected. <html ...

Quickest method for skimming through an extremely lengthy document beginning at any specified line X

In my current project, there is a text file that is written to by a python program and read by another program to display on a web browser. JavaScript handles the reading process at the moment, but I am considering moving this functionality to python. The ...

How come when you add ({}+{}) it equals to "[object Object][object Object]"?

I ran the following code: {}+{} = NaN; ({}+{}) = "[object Object][object Object]"; What is the reason behind the difference in result when adding ()? ...

I'm having trouble figuring out why my Vue method isn't successfully deleting a Firebase object. Can anyone offer some guidance

What I am trying to achieve: I have been struggling to use the remove method from Firebase. I have read the documentation, but for some reason, it is not working as expected. Retrieving data using snapshot works fine, but when I try to delete using the re ...