DEV Community

Cover image for Pass props to an Emotion component
Paul Ryan
Paul Ryan

Posted on

Pass props to an Emotion component

So cool!

This is a quick post but said I share as I think it's really cool as you can essentially pass component props into your styles!!

We will use my own trusty sandbox that I normally use, we will change the background image by passing an image prop to the Card component.

So let's pick a sexy picture from unsplash, let's use this one:
Cool unsplash image

We will use this as our background image, in the index.js file pass the image link to the Card component. I shortened the image link as the original is a beast!

render() {
    return <Card image={''} handleClick={this.handleClick} />;

Now in the Card component destructure the image from props and pass image to our emotion Component

const Card = ({ handleClick, image }) => {
  return (
    <Component image={image}>
      <div className="card">

Now the big question is, how do we get this to our styled component seeing as it looks like we can't pass it props?

It's actually quite simple, we need to do this, essentially using an arrow function to get our props:
props => props.image

So in our case, we just need to do the following:

const Component = styled("card")`
  .card {
    background-image: url('${props => props.image}');

And voila it is done! I absolutely love this feature, makes it so easy to make components completely self-contained.

Final CodeSandbox:

I currently have 99 followers on Twitter so it would be great if you could become my 100!

Top comments (2)

rmcsharry profile image
Richard McSharry • Edited

Thanks for posting this, very helpful indeed! I became your 718th follower on Twitter - maybe time to chnage that 'become 100' to 'become 1000' !

paulryan7 profile image
Paul Ryan

114th follower and thanks very much for following