I'm using CRA with Material-ui and Styled Components type of styling. When building my CSS I want to access Material-ui's default theme.
part of package.json:
"dependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"@material-ui/core": "^4.2.1",
"@material-ui/icons": "^4.2.1",
"@material-ui/styles": "^4.2.1",
"styled-components": "^4.3.2"
}
When I try the below theme
exists on props
but is an empty object.
StyledApp.js:
import styled from "styled-components";
import Button from "@material-ui/core/Button";
export const StyledButtonUsingTheme = styled(Button)`
//Below will give "Cannot read property 'error' of undefined"
background-color: ${props => props.theme.palette.error.light};
`;
App.js:
import React from "react";
import "./App.css";
import { StylesProvider, ThemeProvider } from "@material-ui/styles";
import { createMuiTheme } from "@material-ui/core/styles";
import { StyledButtonUsingTheme } from "./StyledApp";
function App() {
const defaultTheme = createMuiTheme();
window.console.log("Default theme passing to ThemeProvider", defaultTheme);
return (
<StylesProvider injectFirst>
<ThemeProvider theme={defaultTheme}>
<div className="App">
<StyledButtonUsingTheme variant="outlined">
Styled Button Using Theme
</StyledButtonUsingTheme>
</div>
</ThemeProvider>
</StylesProvider>
);
}
export default App;
The console.log in App.js
shows the whole theme object, and that's what I pass to ThemesProvider. Interestingly props.theme
is there! but sadly with no values.
theme
toStyledButtonUsingTheme
in any way. I don't see how this can work – Assemblymanstyled
from the wrong place.import { styled } from '@material-ui/styles';
– Assemblyman