Can't get custom theme of Material UI to work - javascript

I'm trying to create a custom theme for my app using Material UI. Looking on how to do it, I found out I had to use the createTheme and the ThemeProvider. However for some reason, my theme is not overriding the default theme. In the following code you'll be able to see that I try to override the primary color with a brownish color, yeth the default blue still persists.
import {Button} from "#material-ui/core";
import {createTheme, ThemeProvider} from "#material-ui/core"
import {makeStyles} from "#material-ui/core";
const theme = createTheme({
pallete: {
primary: {
main: '#923223'
}
}
})
const App = () => {
return (
<ThemeProvider theme={theme}>
<div style={{backgroundColor: '#f8f8f8', height: '100%'}}>
<Button variant="contained" color="primary">algo</Button>
</div>
</ThemeProvider>
);
}
export default App;
Render:
Any clue to what's going on?

Related

Can you use Chakra-UI's colorMode to change the background color to any color or is it only for light and dark mode?

This is my theme file. For now it only toggles between light and dark mode. I was wondering if I can pass in different colors or do I need to create a hook myself to do that?
import { extendTheme } from '#chakra-ui/react'
// 2. Add your color mode config
const config = {
initialColorMode: '#C53030',
useSystemColorMode: true,
}
// 3. extend the theme
const theme = extendTheme({ config })
export default theme
If you intend to customise the default theme object to match your design requirements, you need to extend the theme.
Chakra UI provides an extendTheme function that deep merges the default theme with your customizations.
// pages/_app.js
import { ChakraProvider } from '#chakra-ui/react'
// 1. Import the extendTheme function
import { extendTheme } from '#chakra-ui/react'
// 2. Extend the theme to include custom colors, fonts, etc
const colors = {
brand: {
900: '#1a365d',
800: '#153e75',
700: '#2a69ac',
},
}
const theme = extendTheme({ colors })
// 3. Pass the `theme` prop to the `ChakraProvider`
function MyApp({ Component, pageProps }) {
return (
<ChakraProvider theme={theme}>
<Component {...pageProps} />
</ChakraProvider>
)
}
export default MyApp;
that comes from the get-started page of chakra and I hope it answers "how to change the background color to any color"
You can set the background and text colour using the semantic tokens:
"chakra-body-text" and "chakra-body-bg", with their respective _light and
_dark keys.
You can see this in action (and toggle the theme) here:
https://codesandbox.io/s/chakra-ui-theme-bg-ty5qt0
I couldn't find this specific issue documented, but here are related links:
https://chakra-ui.com/docs/styled-system/color-mode
https://chakra-ui.com/docs/styled-system/semantic-tokens
https://github.com/chakra-ui/chakra-ui/blob/main/packages/components/theme/src/semantic-tokens.ts
import * as React from "react";
import * as ReactDOMClient from "react-dom/client";
import { ChakraProvider, extendTheme } from "#chakra-ui/react";
import App from "./App";
const theme = extendTheme({
semanticTokens: {
colors: {
"chakra-body-text": {
_light: "purple.800",
_dark: "pink.100",
},
"chakra-body-bg": {
_light: "pink.100",
_dark: "purple.800",
},
},
},
});
const rootElement = document.getElementById("root");
const root = ReactDOMClient.createRoot(rootElement);
root.render(
<ChakraProvider theme={theme}>
<App />
</ChakraProvider>
);

Wild error after importing material UI in React app

I am trying to style my project with material UI and i am getting this unfamiliar error.
I've tried restarting my project multiple times. To no avail.
This is the error from my console:
ERROR in ../../../../../node_modules/#babel/runtime/helpers/esm/toConsumableArray.js 4:0-52
Module not found: Error: Can't resolve './nonIterableSpread' in '/Users/HP/node_modules/#babel/runtime/helpers/esm'
Did you mean 'nonIterableSpread.js'?
...
Navbar.js
import React from "react";
import { makeStyles } from "#material-ui/core/styles";
const useStyles = makeStyles((theme) => ({
root: {
display: "flex",
},
}));
function Navbar() {
const classes = useStyles();
return (
<>
<header className={classes.root}>
<div className="title">
<h1>Mba Okocha</h1>
</div>
</header>
</>
);
}
export default Navbar;

Using custom styles from theme in material ui without makeStyles

I'm wondering if there is a way to access theme.customElements.acitonButton in MyComponent without having to use makeStyles? For example, can I somehow enter className={theme.customElements.actionButton}?
theme.js
const theme = createMuiTheme({
customElements: {
actionButton: {
backgroundColor: '#007AFF'
}
}
})
export default theme
MyComponent.tsx
import { makeStyles, createStyles, Theme } from '#material-ui/core'
// wondering if i can remove makeStyles and somehow access styles set in theme.js and add to <IconButton />?
const useStyles: any = makeStyles((theme: Theme) => {
return createStyles({
actionButton: theme.customElements.actionButton
})
})
const MyComponent: React.FunctionComponent<MyComponentProps> = props => {
const classes = useStyles()
<IconButton className={classes.actionButton} />
}
You can override the style of a Component or Element in the theme.
To do that, you need to create the a folder called overrides in theme folder and create a file with the same name as the component whose theme you want to override.
Then you can change the component style like this.
export default {
elevation1: {
boxShadow: '0 0 0 1px rgba(63,63,68,0.05), 0 1px 3px 0 rgba(63,63,68,0.15)'
}
};
Also you need to add the theme provider to App.js.
import React from 'react';
import ThemeProvider from '#material-ui/styles/ThemeProvider';
import CssBaseline from '#material-ui/core/CssBaseline';
import {darkBlueTheme} from './theme';
import Routes from './Routes';
function App() {
return (
<StateProvider reducer={appReducer} initialState={getInitialState()}>
<ThemeProvider theme={darkBlueTheme}>
App CODE HERE
</ThemeProvider>
</StateProvider>
);
}
export default App;

How to theme components with Styled-Component and Material-UI

I've tried to follow exactly what's documented here:
How to theme components with styled-components and Material-UI?
import React from "react";
import { withTheme } from "#material-ui/core/styles";
import styled from "styled-components";
const StyledDiv = withTheme(styled.div`
background: ${props => props.theme.palette.primary.main};
color: ${props => props.theme.palette.primary.contrastText};
`);
export default function App() {
return (
<StyledDiv>
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</StyledDiv>
);
}
But instead of using a "standard" HTML component like above I tried against a Material-UI Button with no luck. Can someone please help me with what I am doing wrong?
This is what I am trying:
styles.ts
import styled from 'styled-components';
import { withTheme } from "#material-ui/core/styles";
import { Button } from '#material-ui/core';
export const StyledInnerSignInButton = withTheme(styled(Button)`
margin: ${props => props.theme.spacing(3, 0, 2)};
`)
index.tsx
import { StyledInnerSignInButton } from './styles';
[...]
<StyledInnerSignInButton
type="submit"
fullWidth
variant="contained"
color="primary"
>
Sign In
</StyledInnerSignInButton>
I'm stuck here and still a React newbie. Any help is greatly appreciated!
I managed to resolve my issue. It was due to specificity. There are two ways to mitigate that, one is by wrapping the new component style with &&, for example:
export const StyledInnerSignInButton = withTheme(styled(Button)`
&& { margin: ${props => props.theme.spacing(3, 0, 2)}; }
`)
Or by manipulating the CSS Injection Order, as documented here
In your "master" index.tsx file, you will set up your code this way:
import React from 'react';
import { render } from 'react-dom';
import { StylesProvider } from '#material-ui/core/styles';
import Home from './pages/Home';
render(
<React.StrictMode>
<StylesProvider injectFirst>
{/* component name */}
<Home />
</StylesProvider>
</React.StrictMode>,
document.getElementById('root')
)
I hope that helps someone with the same problem as me.

Importing a dynamic MaterialUI theme object from a separate file?

Can someone help me understand the correct syntax for allowing a dynamic theme object to be imported from a separate file?
I am trying to get the system theme from a media query and then set the theme dynamically.
This works fine if I leave everything all in the main App function like this:
https://stackblitz.com/edit/theme-builder-working-all-in-one?file=index.js
But I want to have it broken up into different files for organization in the example below but my attempt is broken, I get the error: themeProvider_js_1.default is not a function
broken example:
https://stackblitz.com/edit/theme-builder-broken?file=index.js
This is a second try of refactoring, no errors, I can see the ThemeObject existing in the console log but the system theme isn't being applied:
https://stackblitz.com/edit/theme-builder-broken-btyufg?file=index.js
Code for the future:
working code, but I want to refactor this so the theme and media query objects are outside of the App component:
import React from 'react';
import { render } from 'react-dom';
import useMediaQuery from '#material-ui/core/useMediaQuery';
import { createMuiTheme, ThemeProvider } from '#material-ui/core/styles';
import CssBaseline from '#material-ui/core/CssBaseline';
function App() {
const prefersDarkMode = useMediaQuery('(prefers-color-scheme)');
const theme = React.useMemo(
() =>
createMuiTheme({
palette: {
type: prefersDarkMode ? 'dark' : 'light',
},
}),
[prefersDarkMode],
);
return (
<ThemeProvider theme={theme}>
<CssBaseline/>
<p>
Start editing to see some magic happen :)
</p>
</ThemeProvider>
);
}
render(<App />, document.getElementById('root'));
broken refactor attempt:
App component
import React from 'react';
import { render } from 'react-dom';
import useMediaQuery from '#material-ui/core/useMediaQuery';
import { createMuiTheme, ThemeProvider } from '#material-ui/core/styles';
import themeBuilder from './themeProvider.js'
function App() {
return (
<ThemeProvider theme={themeBuilder()}>
<p>
Start editing to see some magic happen :)
</p>
</ThemeProvider>
);
}
render(<App />, document.getElementById('root'));
themeBuilder
import React from 'react';
import { createMuiTheme } from '#material-ui/core/styles';
import useMediaQuery from '#material-ui/core/useMediaQuery';
function themeBuilder() {
const prefersDarkMode = useMediaQuery('(prefers-color-scheme)');
const theme = React.useMemo(
() =>
createMuiTheme({
palette: {
type: prefersDarkMode ? 'dark' : 'light',
},
}),
[prefersDarkMode],
);
return theme
}
I think you're missing export default in themeProvider.js
export default function themeBuilder() {
const prefersDarkMode = useMediaQuery('(prefers-color-scheme)');
const theme = React.useMemo(
() =>
createMuiTheme({
palette: {
type: prefersDarkMode ? 'dark' : 'light',
},
}),
[prefersDarkMode],
);
return theme
}

Categories