What is best practice of 'ThemeProvider' in styled-components? - reactjs

I wanna know where <ThemeProvider/> should be placed in React app.
I'd come up with two solutions about it.
1, <ThemeProvider/> should be used 'Just Once' in top-root component
like index.js or App.js file created by 'create-react-app' tool.
2, <ThemeProvicer/> should be placed in 'Each root of React-component'
literally.
for clarification, I'll show you some example.
there is just two component, 'Red' and 'Blue' <div> tag.
1, <ThemeProvider/> used 'Just Once'
// In './red.js'
import React from 'react'
import styled from "styled-components"
const Red = styled.div`background: ${props => props.theme.mainColor}`
export default function RedDiv() {
return (
//NOT using ThemeProvider
<Red />
)
}
// In './blue.js'
......
const Blue = styled.div`background: ${props => props.theme.subColor}`
export default function BlueDiv() {
return (
<Blue />
)
}
// In './App.js'
import React, { Component } from 'react'
import { ThemeProvider } from "styled-components"
import myTheme from "./myTheme
import Red from "./red"
import Blue from "./blue"
export default class App extends Component {
render() {
return (
//only used here just once
<ThemeProvider theme={myTheme}>
<>
<Red />
<Blue />
</>
</ThemeProvider>
)
}
}
2, <ThemeProvider/> used 'Each root of React-component'
// In './red.js'
import React from 'react'
import styled, { ThemeProvider } from "styled-components"
const Red = styled.div`background: ${props => props.theme.mainColor} `
export default function RedDiv() {
return (
<ThemeProvider theme={myTheme}>
<Red />
</ThemeProvider>
)
}
// In './blue.js'
......
const Blue = styled.div`background: ${props => props.theme.mainColor}`
export default function BlueDiv() {
return (
<ThemeProvider theme={myTheme}>
<Blue />
</ThemeProvider>
)
}
// In './App.js'
import React, { Component } from 'react'
import Red from "./red"
import Blue from "./blue"
export default class App extends Component {
render() {
return (
<>
// <ThemeProvider/> is not used
<Red />
<Blue />
</>
)
}
}
there is maybe some typo on the code above, but I hope that this example will convey my idea clearly.

I use it only once, inside index.js.
Also a good place to add some global styles, if you need them. I use them for resetCSS (http://meyerweb.com/eric/tools/css/reset/) and some baseCSS rules like box-sizing etc.
index.js
import { createGlobalStyle, ThemeProvider } from 'styled-components';
import theme from './styles/theme';
import resetCSS from './styles/resetCSS';
import baseCSS from './styles/baseCSS';
import { BrowserRouter as Router} from "react-router-dom";
const GlobalStyle = createGlobalStyle`
${resetCSS}
${baseCSS}
`;
React.DOM.render(
<React.Fragment>
<GlobalStyle/>
<Router>
<ThemeProvider theme={theme}>
<App/>
</ThemeProvider>
</Router>
</React.Fragment>
,document.getElementById('root')
);

Related

override component mui v5 react

I'm using mui v5 and I'm trying to override the Container component to be have a padding of 4rem.
here is a simple code example:
import * as React from "react";
import { Container } from "#mui/material";
import Navbar from "./components/Navbar";
import { styled } from "#mui/system";
import CssBaseline from "#mui/material/CssBaseline";
import { ThemeProvider, StyledEngineProvider } from "#mui/material/styles";
import theme from "./theme";
const MyContainer = styled(Container, {})`
padding-left: 4rem;
background-color: aqua;
`;
export default function App() {
return (
<ThemeProvider theme={theme}>
<StyledEngineProvider injectFirst>
<CssBaseline />
<MyContainer maxWidth="xl">
<div>test</div>
</MyContainer>
</StyledEngineProvider>
</ThemeProvider>,
);
}
But this yields no results.
here is a sandbox:
https://codesandbox.io/s/wizardly-leakey-xumyd
You can use make use of shouldForwardProp of mui v5.
const MyContainer = styled(Container, {
shouldForwardProp: (prop) => prop
})(({ padding }) => ({
padding: padding,
backgroundColor: "aqua"
}));
You can check forked codesandbox here
open this

How to access material theme in shared component in react?

I have two react projects Parent and Common project (contains common component like header, footer)
I have material theme defined in Parent and configured in standard way using MuiThemeProvider.
However, this theme object is available inside components defined in Parent, but not in share project common.
Suggestions are appreciated.
Added below more details on Oct 30, 2020
Parent Component
import React from "react";
import "./App.css";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import themeDefault from "./CustomTheme.js";
import { MuiThemeProvider } from "#material-ui/core/styles";
import { createMuiTheme } from "#material-ui/core/styles";
import Dashboard from "./containers/Dashboard/Dashboard";
import { Footer, Header } from "my-common-react-project";
function App() {
const routes = () => {
return (
<BrowserRouter>
<Switch>
<Route exact path="/" component={Dashboard} />
</Switch>
</BrowserRouter>
);
};
return (
<MuiThemeProvider theme={createMuiTheme(themeDefault)}>
<div className="App">
<Header
logo="some-logo"
userEmail={"test#email"}
/>
... app components here..
<Footer />
</div>
</MuiThemeProvider>
);
}
export default App;
Shared component
import React from "react";
import {
Box,
AppBar,
Toolbar,
Typography,
} from "#material-ui/core/";
import styles from "./Header.styles";
import PropTypes from "prop-types";
const Header = (props) => {
const classes = styles();
const { options, history } = props;
const [anchorEl, setAnchorEl] = React.useState(null);
const handleCloseMenu = () => {
setAnchorEl(null);
};
const goto = (url) => {
history.push(url);
};
return (
<Box component="nav" className={classes.headerBox}>
<AppBar position="static" className={classes.headerPart}>
<Toolbar className={classes.toolBar}>
{localStorage && localStorage.getItem("isLoggedIn") && (
<>
{options &&
options.map((option) => (
<Typography
key={option.url}
variant="subtitle1"
className={classes.headerLinks}
onClick={() => goto(option.url)}
>
{option.name}
</Typography>
))}
</>
)}
</Toolbar>
</AppBar>
</Box>
);
};
Header.propTypes = {
options: PropTypes.array
};
export default Header;
Shared Component style
import { makeStyles } from "#material-ui/core/styles";
export default makeStyles((theme) => ({
headerPart: {
background: "white",
boxShadow: "0px 4px 15px #00000029",
opacity: 1,
background: `8px solid ${theme.palette.primary.main}`
borderTop: `8px solid ${theme.palette.primary.main}`
}
}));
The Parent component defined theme.palette.primary.main as say Red color and I expect same to be applied in Header but it is picking a different theme (default) object which has theme.palette.primary.main blue.
Which results in my header to be in blue color but body in read color.
Any suggestion how to configure this theme object so that header too picks the theme.palette.primary.main from parent theme object.
here is the answer for mui V5
import { useTheme } from '#mui/material/styles' // /!\ I fixed a typo from official doc here
function DeepChild() {
const theme = useTheme();
return <span>{`spacing ${theme.spacing}`}</span>;
}
Taken from mui documentation
You can use either useTheme or withTheme to inject the theme object to any nested components inside ThemeProvider.
Use useTheme hook in functional components
Use withTheme HOC in class-based components (which can't use hook)
function DeepChild() {
const theme = useTheme<MyTheme>();
return <span>{`spacing ${theme.spacing}`}</span>;
}
class DeepChildClass extends React.Component {
render() {
const { theme } = this.props;
return <span>{`spacing ${theme.spacing}`}</span>;
}
}
const ThemedDeepChildClass = withTheme(DeepChildClass);
Live Demo

React: CssBaseLine component doesn't update after Material UI theme changed

I wanted to update CssBaseline component whenever the theme was changed by button, but it didn't.
Whenever button is clicked, theme seemed to be changed, but what CssBaseline did hasn't been changed such as body's background color, etc.
Is there any way to change it?
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App/>
</React.StrictMode>,
document.getElementById('root')
);
App.js
import React, { useState, useEffect } from 'react';
import './App.css';
import { Button, Container } from '#material-ui/core';
import Title from './components/Title';
import { lightTheme, darkTheme } from './libs/Theme';
import { MuiThemeProvider, CssBaseline } from '#material-ui/core';
function App() {
const [theme, setTheme] = useState(darkTheme);
const handleClick = () => {
theme.palette.type === 'dark' ? setTheme(lightTheme) : setTheme(darkTheme);
}
return (
<MuiThemeProvider theme={theme}>
<CssBaseline />
<Button variant="contained" color="primary" onClick={handleClick}>Change Theme</Button>
<Container maxWidth="xl">
<Title />
</Container>
</MuiThemeProvider>
);
}
export default App;
libs/Theme.js
import { createMuiTheme, responsiveFontSizes } from '#material-ui/core';
export const lightTheme = responsiveFontSizes(
createMuiTheme({
palette: {
type: 'light'
}
})
);
export const darkTheme = responsiveFontSizes(
createMuiTheme({
palette: {
type: 'dark'
}
})
);
This is probably the work of <React.StrictMode>. Take those tags out and it should work. You can track this issue: https://github.com/mui-org/material-ui/issues/20708 for the bug and its possible resolution.
Note that this answer was written on MUI latest release v4.11.0

Material UI for React "Cannot read property of 'between'.. " when trying to use theme.breakpoints

Cannot read property of 'between' / 'up'.. when trying to use theme.breakpoints.between.
I've read through the other stackoverflow answers and some of the issues here: https://github.com/mui-org/material-ui/issues and the only solution seems to be using ThemeProvider or MuiThemeProvider, which I've tried but error still exists.
Component file:
import React, { Component } from "react";
import PropTypes from "prop-types";
import { withStyles } from "#material-ui/styles";
import Grid from "#material-ui/core/Grid";
import Logo from "../assets/logo/logo";
const styles = theme => ({
root: {
flexGrow: 1
},
logo: {
[theme.breakpoints.up("md")]: {
padding: "5em"
}
}
});
class Tools extends Component {
render() {
const { classes } = this.props;
return (
<div className={classes.root}>
<Grid container className={classes.logo}>
<Grid item className={classes.logo}>
<Logo name="some-logo" />
</Grid>
</Grid>
</div>
);
}
}
Tools.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(Tools);
App.js
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import MuiThemeProvider from "#material-ui/core/styles/MuiThemeProvider";
class App extends Component {
render() {
return (
<MuiThemeProvider>
<Router>
<div className="App">
<Switch>
<Route exact path="/" render={() => <Home />} />
</Switch>
</div>
</Router>
</MuiThemeProvider>
);
}
}
export default App;
I think withStyles should have been imported from "#material-ui/**core**/styles" in the component file.
Faced the same issue with sloppy installation of material-ui without checking the version used in the project.
Rolled back to the previous version (listed below) and the issue was resolved.
Rolled back versions of:
#emotion/react: 11.4.1 from 11.5.0, and
#mui/material: 5.0.0 from 5.0.4

How to pass Styled-Component theme variables to Components?

Within my React+StyledComponent app, I have a theme file like so:
theme.js:
const colors = {
blacks: [
'#14161B',
'#2E2E34',
'#3E3E43',
],
};
const theme = {
colors,
};
export default theme;
Currently, I can easily use these colors to style my components like so:
const MyStyledContainer = styled.div`
background-color: ${(props) => props.theme.colors.blacks[1]};
`;
The problem is, how do I pass blacks[1] to a Component as the prop of the color to use like so:
<Text color="black[1]">Hello</Text>
Where Text.js is:
const StyledSpan = styled.span`
color: ${(props) => props.theme.colors[props.color]};
`;
const Text = ({
color,
}) => {
return (
<StyledSpan
color={color}
>
{text}
</StyledSpan>
);
};
Text.propTypes = {
color: PropTypes.string,
};
export default Text;
Currently the above is silently failing and rending the following in the DOM:
<span class="sc-brqgn" color="blacks[1]">Hello</span>
Any ideas on how I can get this to work? Thank you
EDIT: Updated to use styled-components withTheme HOC
New answer
You could wrap the component rendering <Text> in the higher order component (HOC) withTheme provided by styled-components. This enables you to use the theme given to the <ThemeProvider> directly in the React component.
Example (based on the styled-components docs):
import React from 'react'
import { withTheme } from 'styled-components'
import Text from './Text.js'
class MyComponent extends React.Component {
render() {
<Text color={this.props.theme.colors.blacks[1]} />;
}
}
export default withTheme(MyComponent)
Then you could do
const MyStyledContainer = styled.div`
background-color: ${(props) => props.color};
`;
Old answer
You could import the theme where you render and pass <Text color={theme.blacks[1]} />.
import theme from './theme.js'
...
<Text color={theme.colors.blacks[1]} />
Then you could do
const MyStyledContainer = styled.div`
background-color: ${(props) => props.color};
`;
You can use defaultProps
import PropTypes from 'prop-types'
MyStyledContainer.defaultProps = { theme }
App.js
App gets theme and passes color to Text
import React, { Component } from 'react'
import styled from 'styled-components'
const Text = styled.div`
color: ${props => props.color || 'inherit'}
`
class App extends Component {
render() {
const { theme } = this.props
return (
<Text color={theme.colors.black[1]} />
)
}
}
export default App
Root.js
Root component passes theme to entire application.
import React, { Component } from 'react'
import { ThemeProvider } from 'styled-components'
import theme from './theme'
import App from './App'
class Root extends Component {
render() {
return (
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>
)
}
}
export default Root
If you're using functional components in React and v4.x and higher styled-components, you need to leverage useContext and styled-components' ThemeContext. Together, these allow you to use your theme settings inside of components that aren't styled-components.
import { useContext } from 'react'
import { ThemeContext } from 'styled-components'
export default function MyComponent() {
// place ThemeContext into a context that is scoped to just this component
const themeProps = useContext(ThemeContext)
return(
<>
{/* Example here is a wrapper component that needs sizing params */}
{/* We access the context and all of our theme props are attached to it */}
<Wrapper maxWidth={ themeProps.maxWidth }>
</Wrapper>
</>
)
}
Further reading in the styled-components docs: https://styled-components.com/docs/advanced#via-usecontext-react-hook

Resources