Styled-components - Override part of theme - reactjs

I'm using styled-components to handle my styling in a react app.
Using the ThemeProvider wrapper, I'm able to get access to my theme in all of my styled components
However, i was wondering if it was possible to override just a part of the theme.
Here's a quick example:
Let's say I got the following theme:
const theme = {
color: 'red';
backgroundColor: 'blue';
}
I pass it to my app:
<ThemeProvider theme={theme}>
<MyStyledComponent>
<p>Hi</p>
<MyStyledComponent>
</ThemeProvider>
MyStyledComponent is a styled div which receives my theme:
import styled, { css } from 'styled-components'
const StyledButton = styled.button`
${props => ({
color: props.theme.color,
background-color: props.theme.backgroundColor,
})}
`
export default StyledButton
If I display this, I will have a blue div with some red text in it.
Now, if I use the following:
<ThemeProvider theme={theme}>
<MyStyledComponent theme={{color: 'green',}}>
<p>Hi</p>
<MyStyledComponent>
</ThemeProvider>
My text will turn green, BUT, no more blue background-color.
Is there a generic way to make sure that custom themes only override the properties that are found in both theme objects ?

The theme used by MyStyledComponentgets indeed totally overridden by the closest ThemeProvider defined.
Previous solution works well but to avoid to duplicate everywhere {{...theme.color, color: 'green'}} for instance, one can create a small wrapper:
const WithMainTheme = ({ theme: localTheme, children, ...props }) => {
return (
<ThemeProvider theme={{ ...theme, ...localTheme }}>
{React.cloneElement(children, props)}
</ThemeProvider>
);
};
which will allow you to write :
<WithMainTheme theme={{ color: "green" }}>
<MyStyledComponent>Hi</MyStyledComponent>
</WithMainTheme>
to get your button with color: green
See this for a running example

you can just do like normal Object in JS using spread operator and overriding the ones you want at the end.
<ThemeProvider theme={theme}>
<MyStyledComponent theme={{...theme,color: 'green'}}>
<p>Hi</p>
<MyStyledComponent>
</ThemeProvider>

Related

Getting access to a color in ThemeProvider React Native

I have a theme like this:
export const theme = {
red: "#CF3721",
darkGrey: "#191919",
white: "#fff",
blue: "#31A9B8",
};
and a ThemeProvider:
<ThemeProvider theme={theme}>
<Navigator />
</ThemeProvider>
How can I get access f.e. to the red color inside styles below? I tried something like this but it doesn't work well. I am using React Native.
<Component
styles={{
fontSize: 20,
color: `${({ theme }) => theme.red}`,
}}
/>
react-theme-provider library exports useTheme hook and withTheme HOC. You can access the theme context with one of those.
const { ThemeProvider, withTheme, useTheme } = createTheming(defaultTheme);
If you're using Functional component you can use useTheme hook.
function App() {
const theme = useTheme();
return (
<Component
styles={{
fontSize: 20,
color: theme.red,
}}
/>
);
}
If you're using Class component you can use withTheme HOC.
class App extends React.Component {
render() {
return (
<Component
styles={{
fontSize: 20,
color: this.props.theme.red,
}}
/>
);
}
}
export default withTheme(App);
You can look for more advanced usages in the docs. https://github.com/callstack/react-theme-provider

react I want to change the background of globalstyle in chakra theme.ts by props

I want to change the background of the body for each page.
For pageA, I want the backgroud to be white, and for pageB, I want the background to be gray.
I have set the background in the global style of chakra ui, and I want to be able to change the background color in props.
// theme.ts
import { extendTheme } from '#chakra-ui/react';
export const theme = extendTheme({
styles: {
global: {
'html, body': {
color: 'black',
background: 'white',
},
},
},
});
_app.tsx
<ChakraProvider theme={theme}>
<App />
</ChakraProvider>
Chakra is using Emotion under the hood, so the background can be customized for each page using Emotion's Global tag as follows:
// pageA.tsx
import { Global, css } from '#emotion/react';
export const PageA: React.FC = () => {
return (
<>
<Global styles={css`body { background-color: hotpink !important; }`} />
Hello world!
</>
);
};

InputProps Material-UI in React

I have to make the TextField in material-ui to be uppercase. Right now, I need to put inputProps={{ style: { textTransform: 'uppercase' } }} in everything TextField. So I have define a theme in my react app for this and I wanted something to look like this.
Please also check picture on how I do them
https://i.stack.imgur.com/lnukB.png
MuiTextField.js
export default {
root: {
textTransform: 'capitalize',
},
};
You can create a theme and override the textTransform to capitalize in every MuiInputBase class of your project, as below:
const theme = createMuiTheme({
overrides: {
MuiInputBase: {
input: {
textTransform: "uppercase"
}
}
}
});
then wrap your project in a ThemeProvider and pass theme as a prop to the ThemeProvider:
ReactDOM.render(
<ThemeProvider theme={theme}>
<Demo />
</ThemeProvider>,
document.querySelector("#root")
);
sandbox link
Using this method, you no longer need to manually add textTransform: "capitalize" to every TextField component.

Material-UI custom theming

I want to create a custom theme and customize some Material-UI components. I followed this customization tutorial provided by Material-UI. With this, I was able to do the following:
Creating costume theme:
//MUI THEMING
import {
createMuiTheme,
makeStyles,
ThemeProvider,
} from "#material-ui/core/styles";
import Theme from "./../../theme";
const useStyles = makeStyles((theme) => ({
root: {
backgroundColor: Theme.palette.primary.main,
},
}));
const theme = createMuiTheme({
normal: {
primary: Theme.palette.primary.main,
secondary: Theme.palette.secondary.main,
},
});
Using costume theme:
<ThemeProvider theme={theme}>
<AppBar
position="static"
classes={{
root: classes.root,
}}>
...
</AppBar>
</ThemeProvider>
As expected, this resulted in a costume colored AppBar:
However, when I tried the same with bottom navigation, -trying to change the default primary color-, I could not get it to work. I figured that based on the tutorial, I have to use "&$selected": in the create them to get it to work, but even with this my best result was something like this:
How do I change the primary color of Bottom Navigation with no label?
Sidenote: While I was searching for the solution, I stumbled on the default theme ovject. How can I access this, how can I overwrite it?
In my project, I create a global MUI theme to override the default theme. In makeStyle you can pass a param theme in the callback function like this to get the whole MUI theme object:
const useStyles = makeStyles(theme => {
console.log(theme) // print mui global theme object
return {...your classes here}
})
After that, copy this object to a new file like muiTheme.js to create your own theme. Change these values in this object that you want to override.
// muiTheme.js
import { createMuiTheme } from '#material-ui/core/styles'
const theme = createMuiTheme({
breakpoints: {
keys: ['xs', 'sm', 'md', 'lg', 'xl'],
values: {
xs: 0,
sm: 600,
md: 960,
lg: 1280,
xl: 1920,
},
},
...
})
export default theme
Then, in index.js, use ThemeProvider to override MUI's theme.
import { ThemeProvider } from '#material-ui/core/styles'
import muiTheme from './theme/muiTheme'
import App from './App'
const Root = () => (
<BrowserRouter>
<ThemeProvider theme={muiTheme}>
<App />
</ThemeProvider>
</BrowserRouter>
)
ReactDOM.render(<Root />, document.getElementById('root'))

Material-UI React: Global theme override for Paper component

I have a React app built with the latest Material-UI component library.
I use many instances of the Paper component. I want to apply margins and padding to all them at once, without manually repeating this process for every instance.
I looked up the Material-UI documentation on the topic, and from what I can tell, the following code should correctly override how Paper looks:
const theme = createMuiTheme({
overrides: {
Paper: {
root: {
padding: '10px',
marginBottom: '10px',
},
},
},
});
Below is where overridden style should apply:
<ThemeProvider theme={theme}>
{/* ... */}
<Paper>
Content goes here
</Paper>
{/* ... */}
</ThemeProvider>
But the overridden values aren't being applied. Any suggestions as to what's going on?
Thanks!
in your App.js add (please note MuiPaper and not Paper):
const theme = createMuiTheme({
overrides: {
MuiPaper: {
root: {
padding: '10px',
marginBottom: '10px'
},
},
}
});
at the same App.js file, wrap your HTML:
class App extends Component {
render() {
return (
<MuiThemeProvider theme={theme}>
<div className="App">
<YourComponent1 />
<YourComponent2 />
...
</div>
</MuiThemeProvider>
);
}
}
this way, any Paper component rendered by React will have your CSS.
BTW, I created MUI schematics module which adds Material UI support, generates several Material UI components automatically and adds general theme rules in App.js. You are welcome to take a look / try it...
You can also use your CssBaseline component if you're already using it for global reset...all depends on how you're structuring your theme.
Eg below is from the Mui docs:
<CssBaseline.js>
const theme = createMuiTheme({
overrides: {
MuiCssBaseline: {
'#global': {
html: {
WebkitFontSmoothing: 'auto',
},
},
},
},
});
// ...
return (
<ThemeProvider theme={theme}>
<CssBaseline />
{children}
</ThemeProvider>
);
You can get more details from the docs here using CssBaseline to inject global theme overrides.
I found out the problem.
The internal component name used for CSS is MuiPaper, not simply Paper. The following produces the desired result:
overrides: {
MuiPaper: {
root: {
padding: '10px',
marginBottom: '10px',
},
},
},
createMuiTheme is depreciated in MUI5.
Instead, you should be using createTheme as follows:
export const myTheme = createTheme({
components:{
MuiPaper:{
defaultProps:{
sx:{
padding: '10px',
marginBottom: '10px'
}
}
}
}
})
Additionally, make sure that you wrap your app in the Theme component and add the CssBaseline component:
import { ThemeProvider } from '#mui/material';
import { myTheme } from './themes/my-theme';
import CssBaseline from '#mui/material/CssBaseline';
<ThemeProvider theme={myTheme}>
<CssBaseline />
<MyApp/>
</ThemeProvider>
Here is the official documentation for MUI5

Resources