How do I change the main color in a Material UI theme palette using React MUI?

Currently, I am utilizing an external template with MUI and would like to change the primary color palette in a project configuration file. My goal is to replicate the existing theme along with all of its configurations (such as typography, breakpoints, etc.) while only making modifications to a few specific values, such as primary and secondary colors. Moreover, I seek a scalable solution that allows for easy addition of more configurations in the future.

I have explored using different ThemeProviders within my application by passing the theme config. To achieve this, I considered creating a customThemeProvider where I could retrieve the current theme and merge it deeply with my customization options. For instance:

import { pink, yellow } from "@mui/material/colors";

const appTheme = {
  palette: {
    primary: yellow,
    secondary: pink,
  }
};

export default appTheme;

The code snippet above illustrates how my themeProvider could potentially function:

import {ThemeProvider, useTheme} from "@mui/material";
import {Theme} from "@mui/material/styles";
import {deepmerge} from "@mui/utils";
import {ThemeOptions} from "@mui/material/styles/createTheme";

const CustomThemeProvider = (props : {customThemeOptions: Partial<ThemeOptions>, children : React.ReactNode})=>{
  const appTheme = useTheme()
  const customTheme = deepmerge(appTheme,props.customThemeOptions)

  return(
    <ThemeProvider theme={customTheme}>
      {props.children}
    </ThemeProvider>
  )
}

export default CustomThemeProvider

Unfortunately, the implementation described above does not yield the desired outcome as the new palette fails to take effect. I have also tried passing a theme rather than a themeOptions or using CreateTheme({palette: {...}}), yet those attempts proved unsuccessful as well.

If you have any insight into what may be causing this issue, or if there exists an alternative solution that can produce similar results, please do share your thoughts.

Thank you for your assistance.

Answer №1

If you're aiming to establish a primary theme along with a nested personalized theme that builds upon the primary configuration and only makes adjustments to a handful of values, the MUI documentation indicates that providing a callback function for the custom theme provider to access and enhance the base is recommended.

Tested out the provided example in this demo website: here

const baseTheme = createTheme({
  typography: {
    body1: {
      fontSize: 24,
      fontWeight: 300,
    },
  },
  palette: {
    primary: pink,
    secondary: deepOrange,
  },
});

// 👇 Creating a customized theme to extend the base theme
const customTheme = (theme: ThemeOptions) =>
  createTheme({
    ...theme,
    palette: {
      ...theme.palette,
      primary: teal,
    },
  });

// 👇 Enclosed within an outer theme provider
const MyCustomProvider = ({ children }) => {
  return <ThemeProvider theme={customTheme}>{children}</ThemeProvider>;
};

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

Implementing a Button Click Event Listener on a Separate Component in React

Currently, my React application incorporates MapBox in which the navbar is its parent component. Within the navbar component, there is a button that collapses the navbar when clicked by changing its CSS class. I also want to trigger the following code snip ...

Scroll-triggered closing of modals in Next Js

I have integrated a Modal component into my Next.JS application, and I have implemented a functionality to close the modal when the user scrolls outside of it. However, this effect is also triggering when the user scrolls inside the modal. How can I modi ...

Unique rephrased text: "Varied wrapping styles in both

Feeling frustrated with a seemingly commonplace issue. Despite the thousands of times it has been asked before, I can't seem to find an answer on Google. I wanted to neatly display my text within one of my cards, but so far I've only achieved th ...

minimize the size of the image within a popup window

I encountered an issue with the react-popup component I am using. When I add an image to the popup, it stretches to full width and length. How can I resize the image? export default () => ( <Popup trigger={<Button className="button" ...

Guide to activating the isActive status on a live link within a map iteration utilizing the NEXTUI navigation bar

Check out the new NEXTUI navbar I'm using: I am having trouble setting the isActive property on the active link in my NavBar component in Next.js. I couldn't find much help on Google, so I'm hoping someone here has experience with this or k ...

How do you display a nested object in React after merging it?

To display the JSON below as an image, click https://i.stack.imgur.com/tixu4.png let finalSplit = [ { start: "73", end: "76", splits: [ { word: "Now", start: "73", ...

Avoiding unlimited re-renders when using useEffect() in React - Tips and Strategies

As a new developer, I recently built a chat application using socket io. In my code, I have the useEffect hook set to only change when the socket changes. However, I also have setMessage within the body of useEffect(), with socket as a dependency. Unfortun ...

How do I incorporate scrolling into Material-UI Tabs?

I am currently incorporating Material-ui Tablist into my AppBar component. However, I am facing an issue with the responsiveness of the tabs. When there are too many tabs, some of them become hidden on smaller screens. For more information on the componen ...

Issue encountered during Firebase deployment: Module '@babel/runtime/helpers/builtin/interopRequireDefault' not found

Struggling to deploy firebase functions and encountering multiple issues. During the deployment process, facing a babel error: Error: Cannot find module '@babel/runtime/helpers/builtin/interopRequireDefault' at Function.Module._resolveFilen ...

Making a POST request to a Next.js API route results in a 500 Internal Server Error being sent back

Check out the code in createComment.ts file, which serves as a Next.js api route: import type { NextApiRequest, NextApiResponse } from 'next' import sanityClient from "@sanity/client" const config = { dataset: process.env.NEXT_PUBLI ...

Guide on how to pass the chosen dropdown value from a custom component back to the main component

I've developed a customized MUI select component in React and have integrated it multiple times within another component as shown: customDropdown.js import * as React from 'react'; import FormControl from '@mui/material/FormControl&ap ...

Enhancing React Performance: Storing Component Identity in Redux State

Can I safely pass this to a Redux action creator from a component defined using React.createClass? In my code, I have created the following reducer: const unsavedChangesProtectionReducer = handleActions({ [ENABLE_UNSAVED_CHANGES_PROTECTION]: (unsaved ...

I am struggling to apply custom CSS styles to the scrollbar within a Card component using MUI react

import React from "react"; import Card from "@mui/material/Card"; import CardActions from "@mui/material/CardActions"; import CardContent from "@mui/material/CardContent"; import CardMedia from "@mui/material/Ca ...

Error in React Bootstrap: ReferenceError - 'openModal' is not defined

Whenever the button is clicked, my intention is for a modal to open. I have written the code for it, but I'm encountering errors that I can't seem to resolve. Here's the snippet of my code: import React from "react"; import { M ...

What is the best way to dynamically insert an object into a field name in react-final-form?

When using the react-final-form component, you can expect the following result: <Field name="answers[0].name" component="input" type="radio" value="0" /> { answers: [ { name: 'value' } ] ...

Developing a transparent "cutout" within a colored container using CSS in React Native (Layout design for a QR code scanner)

I'm currently utilizing react-native-camera for QR scanning, which is functioning properly. However, I want to implement a white screen with opacity above the camera, with a blank square in the middle to indicate where the user should scan the QR code ...

ReactJS Application: Issue with Selective Mobile Scrolling

I've been working on a ReactJS web app where we mainly use styled-components for styling, but also sometimes utilize index.css for global styles (such as body and html). The application consists of an app header, a page header, and a container with a ...

Map failing to refresh

Having some trouble with the map function as it's not updating my select box with the new selected value. The issue occurs within a material UI dialog that appears when viewing a file. I notice that the values get updated only after closing and reopen ...

The final version of the React App is devoid of any content, displaying only a blank page

As a beginner in learning React, I must apologize for any basic issues I may encounter. I recently created a shoe store App (following this helpful tutorial on React Router v6) Everything seems to be working perfectly in the development build of my app. ...

Can anyone recommend a speedy sorting algorithm for an extensive list of objects in JavaScript?

Struggling to organize a large array of 2000 elements in ReactJS using JavaScript. The array includes: data = [ { index: 0, id: "404449", product_name: "ette", brand_name: "Dyrberg/Kern", base_pri ...