loading...
Cover image for Using Emotion in React

Using Emotion in React

paulryan7 profile image Paul Ryan ・2 min read

Introduction

CSS-in-JS is a hotly debated topic, personally, I believe you should focus on shipping and using whatever the hell you want! Nevertheless, emotion is quite a nice tool and I am quickly going to show you how to get up and running with it.

I have created the following component but the problem is all the styles live in the style.css file, we will convert this to use emotion.

The starter sandbox is here:

Installing Emotion

You need two dependencies in order to use emotion
@emotion/core
@emotion/styled

So add these to your project or npm install if you are working locally.

Add the styles to the component

Take a look at the following code where we are styling our component within the JS file.

import React from "react";
import styled from "@emotion/styled";

const Component = styled("card")`
  .card {
    background-image: url("https://i.pinimg.com/originals/1c/97/df/1c97df47df64fe9357290bd7f51d0a1a.jpg");
    background-repeat: no-repeat;
    background-size: 200px 350px;
    height: 350px;
    width: 200px;
    position: relative;
    display: flex;
    justify-content: center;
  }

... more styles
`;

const Card = ({ handleClick }) => {
  return (
    <Component>
      <div className="card">
        <div className="text">
          <div className="action">
            <span>VISIT</span>
          </div>
          <div className="country">
            <span>Iceland</span>
          </div>
        </div>
        <button onClick={handleClick}>DISCOVER</button>
      </div>
    </Component>
  );
};

export default Card;

As you can see from above, we create a new component called Component and assign it to styled(Card), then we use a template literal to insert our styles.

This is a great way to keep your css scoped and also keep the css in the same file as the component. If in the future we needed to remove this component, we wouldn't have to worry about finding all the styles associated with it as they all live in the same file. SO GREAT!

Import colors

Since we are using JS, we can import colors from an object and add it to our component.

Create a file called colors.js and add the following:

export default {
  dark: "#333"
};

Now in the component we can import the colors with:
import color from '../../colors'

We can then use the dark color like so:

button {
    background-color: ${color.dark};
    ....
}

That's all folks!

That is about it, this is really just the basics but is more than enough to get you up and going!

Final Example:

Posted on by:

paulryan7 profile

Paul Ryan

@paulryan7

Developer hailing from Ireland, love all things JS and starting to fall in love with SVGs!

Discussion

markdown guide