Mui v5 cannot apply color defined in custom theme

Viewed 287

I made a small custome theme in mui v5 which is below

  import React from "react";
  import { createTheme, Theme } from "@mui/material/styles";
  import { brown, red } from "@mui/material/colors";

export const theme = createTheme({
  palette: {
    primary: {
      main: "#000000",
      magic: "#000000",
    },
    brown: {
      main: brown[300],
    },
    promoColor: {
      main:red[800]
    },
  },
  myField: {
    myNestedField: { margin: "10px 5px" },
  },
});

and then passed this into the context in my root file

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <ThemeProvider theme={theme}>
        <PersistGate persistor={persistor}>
          <ApolloProvider client={client}>
            <App />
          </ApolloProvider>
        </PersistGate>
      </ThemeProvider>
    </Provider>
  </React.StrictMode>,
  document.getElementById("root")
);

but the issue is that, when i am trying to use the theme color of primary.magic in a button like

 <Button type="submit" variant="contained" color={theme.palette.primary.magic}>
  Submit
  </Button>

i get an error which says

Uncaught TypeError: theme.palette[ownerState.color] is undefined

and when i do it like

<Button type="submit" variant="contained" color="primary">
    Submit
    </Button>

it works fine, but i want to add "magic" color in my button

1 Answers

Try to use the sx property:

<Button
  type='submit'
  variant='contained'
  sx={{ backgroundColor: 'primary.magic' }}
>
  Submit
</Button>;
Related