Not able to access theme in styled component using @emotion/styled

Viewed 2250

enter image description here

I'm using @emotion/react to theming and injected theme into it, I'm able to access theme using useTheme into component but not able to access theme into styles using @emotion/styled. Any help please?

//libs
import React from 'react';
import styled from '@emotion/styled';

import StylesProvider from '@mui/styles/StylesProvider';
import { ThemeProvider } from '@emotion/react';


const THEME = {
  primary: 'red'
}

const StyledText = styled('p')`
  color: ${({ theme }) => theme.primary};
`;

function App() {
  return (
    <StylesProvider injectFirst>
      <ThemeProvider theme={THEME}>
        <StyledText>test</StyledText>
      </ThemeProvider>
    </StylesProvider>
  );
}

export default App;



here is sample code
2 Answers

You need to call it like this. See this section for more detail.

const StyledTextField = styled('div')(({ theme }) => `
  margin: ${theme.spacing(1)};
  background-color: ${theme.palette.primary.main};
  /* ... */
`);

Or you can also use the JS object like in the docs:

const StyledTextField = styled('div')(({ theme }) => ({
  margin: theme.spacing(1),
  backgroundColor: theme.palette.primary.main,
  // ...
}));

Codesandbox Demo

  1. Create "emotion.d.ts" and declare your Theme:
import "@emotion/react";

declare module "@emotion/react" {
  export interface Theme {
    color: {
      primary: string;
    }
  }
}
  1. Import Definitely Type file "emotion.d.ts" into "tsconfig.ts":
"typeRoots": ["emotion.d.ts"]
  1. Reload Window and use it like this:
const StyledText = styled('p')`
  color: ${({ theme }) => theme.color.primary};
`;
  1. If you use Mui, let's extends your Theme:
export interface Theme extends ThemeOfMui{}
Related