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

Time:06-03

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?

CodePudding user response:

It might be helpful if you show the other attributes you're passing in the styles object. Post the code for the 'div' component and the output of log errors if possible.

Another question, but I don't think this was the main issue: I think it might be a good practice if you use your "div" component in camelCase syntax, like 'DivComponent', for example. To avoid confusing it with the 'div' html tag.

CodePudding user response:

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
})

  • Related