mufasa
mufasa

Reputation: 1344

How to use emotion/styled with React and Typescript

I have wrapped my root component in ThemeProvider from @emotion/react which gives me access to props.theme as such:

const StyledDiv = styled.div`
  background-color: ${(props) => props.theme.palette.primary.main};
`;

Problem: props.theme is an empty object according to TS - palette does not exist on the Theme type (however the object I am passing to the theme provider does contain that attribute). If I make TS ignore this, the code works.

The docs cover this and it seems like an easy fix: Extend the Emotion theme type

However I do not understand the docs well enough to make the Theme type of props.theme have the correct attributes.

Any help that points me in the right direction is much appreciated!

Upvotes: 7

Views: 2986

Answers (1)

Sebastián Cabeza
Sebastián Cabeza

Reputation: 96

Add this file types.d.ts

import "@emotion/react";
import { IPalette } from "../your-palette";

declare module "@emotion/react" {
  export interface Theme extends IPalette {}
}

Upvotes: 7

Related Questions