Search code examples
reactjsreact-propsemotion

Styles not applied at child component with Emotion 11 css prop in Gatsby and Typescript project


I'am using Emotion CSS prop to style my Gatsby / Typescript application.

I am using Gatsby 2 and Emotion 11.

In e.g. my Header component I render a Logo component:

/** @jsx jsx */
import { FC } from 'react';

import { jsx } from '@emotion/react';

import Logo from 'components/Logo';
import useSiteMetaData from 'hooks/useSiteMetadata';

import Styles from './Header.styles';
import { Props } from './Header.types';

const Header: FC<Props> = () => {
  const styles = Styles();
  const { title } = useSiteMetaData();

  return (
    <header css={styles.root}>
      <Logo siteTitle={title} css={styles.logo} />
    </header>
  );
};

export default Header;

But on the css prop of my child component I get a Typescript error:

Property 'css' does not exist on type 'IntrinsicAttributes & Props'.ts(2322)

I added below to tsconfig.json and that solves the linting error:

{
  "compilerOptions": {
    "types": ["@emotion/react/types/css-prop"],
  }
}

But somehow the styles are not applied from within my Header.styles.ts, so I am able to overwrite/add some styles of my child component (Logo)?


Solution

  • You have such example in css-prop docs.

    The P component acts like your Logo component, and ArticleText is your Header

    const P = props => (
      <p
        css={{
          margin: 0,
          fontSize: 12,
          lineHeight: '1.5',
          fontFamily: 'sans-serif',
          color: 'black'
        }}
        {...props} // <- props contains the `className` prop
      />
    )
    
    const ArticleText = props => (
      <P
        css={{
          fontSize: 14,
          fontFamily: 'Georgia, serif',
          color: 'darkgray'
        }}
        {...props} // <- props contains the `className` prop
      />
    )
    

    You mean need to pass the className prop, see related answer.