1

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?

2
  • Hey, I would like to recommend you to have a look at the props. You are assigning value to css prop where as i feel it should be style. Commented Jun 3, 2022 at 7:20
  • Possible duplicate of stackoverflow.com/questions/46710747/… Commented Jun 3, 2022 at 7:40

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, that seems to do it. Weird, I had always been using plain objects with no issue and only noticed once I had to use the position prop. Thank you!
0

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.

2 Comments

Regarding initial part its very well indicated in the question that when the value is assigned with a general value it works e.g color: 'green' but does not work when another property is added for example position: 'absolute'. One more thing regarding 'DivComponent' there is no mentioning of such component in the original question. What's build the assumption regarding 'DivComponent'.
Oh, it's a regular div, I actually don't like the styled component syntax to be honest, it feels a bit inflexible to me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.