reactjstypescriptemotioncss-in-js

TS error using css "position" when passing style object to Emotion's css prop


I have a React component roughly with this structure:

    // This does not work.
    const style = {
       position: 'absolute'
       // ...other css props
    }
    
    const Component = () => {
       return <div css={style}/>
    }

That structure seems to work for all other css props but if I include the position prop in the object, I get the following TypeScript errors:

Type '{ //... }' is not assignable to type 'Interpolation<Theme>'

Type '{ //... }'is not assignable to type 'undefined'. TS2322

Passing the position prop directly inline to the css prop works just fine:

   // This works.
   const style = {           
      // ...other css props
   }
    
   const Component = () => {
      return <div css={{ position: 'absolute', ...style }}/>
   }

Any idea of why I can´t include the position prop in the style object?


Solution

  • It's because you are using plan object value as css prop value for emotion directly. Only direct input of css style object into css prop would work with emotion.

    Please check https://emotion.sh/docs/object-styles.

    To use css style object, you need to define it as emotion's Style Object using css.

    const style= css({
      position: 'absolute',
      ...otherStyles
    })