I'm using MUI's theming capabilities. I have a file theming.js
that has:
import { createTheme } from '@mui/material/styles';
export const myTheme = createTheme({
palette: {
primary: {
main: '#BD72A8',
},
secondary: {
main: '#00A0BE',
},
},
});
I'm attempting to create a styled component that draws on the theme's palette. Here's what I have so far:
import { withTheme } from "@material-ui/core/styles";
const LeftSidebar = withTheme(styled.div`
display: inline-block;
width: 25%;
border: 2px solid ${props => props.theme.palette.secondary.main};
border-radius: 4px;
`);
return (
<ThemeProvider theme={myTheme}>
<LeftSidebar>
...
</LeftSidebar>
</ThemeProvider>
)
The styles component LeftSidebar
is picking up the other styles I define, but it's not using the secondary color on my palette as defined in theming.js
. In fact, it looks like it's falling onto a different definition of 'theme', because this code results in the border's color being #f50057 - not the secondary color I chose at all, but also not blank.
Can anybody help me understand what I'm doing wrong in trying to combine MUI and styled components?
Inspired by this SO question, I kept tinkering around and learned that it wasn't working because I was using the ThemeProvider
from MUI, whereas it works if I use the ThemeProvider
from styled-components. In other words, this now works:
import styled, { ThemeProvider } from 'styled-components';
const LeftSidebar = styled.div`
...
border: 2px solid ${props => props.theme.palette.secondary.main};
`;
...
<ThemeProvider theme={mnemoTheme}>
<LeftSidebar>
...