Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

229
Visualizações
Material ui use palette primary color based on selected theme mode

While using mui react, I want to color some non material ui custom components made with div using colors from my theme's primary palette.

I currently can use theme.palette.primary.main or the .light colors directly, including the theme.palette.text.primary for texts colors.

But if I change the theme to dark mode, I will have to change the color reference as well, by checking on theme.mode with conditionals like the following:

  <div
    style={{
      backgroundColor:
        theme.palette.mode == "light"
          ? theme.palette.primary.dark
          : theme.palette.primary.light
    }}
  >
    Test
  </div>

So is there a way we can make this work just like in the material ui components? Passing theme.palette.primary will work with theme mode changes?

Maybe something simpler like:

<div style={{ backgroundColor: theme.palette.primary }}></div>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could use Context to save your theme setting globally and also you need to separate the themes like light and dark.

// SettingsContext.js
import React, {
  createContext,
  useState
} from 'react';

const defaultSettings = {
  // you could add sort of global settings here
  theme: 'light'
};

const SettingsContext = createContext({
  settings: defaultSettings,
  saveSettings: () => {}
});

export const SettingsProvider = ({ settings, children }) => {
  const [currentSettings, setCurrentSettings] = useState(settings || defaultSettings);

  return (
    <SettingsContext.Provider
      value={{
        settings: currentSettings,
      }}
    >
      {children}
    </SettingsContext.Provider>
  );
};

export const SettingsConsumer = SettingsContext.Consumer;

export default SettingsContext;

You can build the settings context as a hook but you can skip this.

// useSettings.js
import { useContext } from 'react'; 
import SettingsContext from './SettingsContext';

const useSettings = () => useContext(SettingsContext);

export default useSettings;

And then try to create your custom theme which includes the dark and light mode.

// theme.js
import { createTheme as createMuiTheme } from '@mui/material/styles';

const themes = {
  'light': {
    ...
  },
  'dark': {
    ...
  }
];

export const createTheme = (name) => {
  return createMuiTheme(themes[name]);
}

After that, you need to pass the theme which you have selected in App.js or index.js whatever top level file.

// App.js
...
import { ThemeProvider } from '@mui/material/styles';
import useSettings from './useSettings';
import { createTheme } from './theme.js';

const App = () => {
  const { settings } = useSettings();

  const theme = createTheme(settings.theme);

  return (
    <ThemeProvider theme={theme}>
      ...
    </ThemeProvider>
  );
};

export default App;
...

That's all.

Now you can use the selected theme without conditional render in your components.

<div style={{ backgroundColor: theme.palette.primary }}></div>

But this will not prevent the selected theme after hard refresh.

So if you want to keep the theme as selected even after refresh your browser, then you could save the theme setting in the localStorage.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda