EmotionJS: Style effectively!!

Photo by Tengyart on Unsplash

Well, I cant deny that the name of the library also caught my attention to look more into it. The above image demonstrates emotions in expressions!

Likewise EmotionJS use expressions to effectively build styles of UI components in an application.

Logo of EmotionJS library

A CSS-in-JS library designed for writing CSS styles with JavaScript.

  • It allows you to style apps quickly.
  • It accepts strings and objects.
  • Has support for auto vendor-prefixing, nested selectors, and media queries.

One of the very powerful patterns CSS-in-JS enables is state-based styling. Technically it is usually implemented as a JavaScript function which receives a state object and returns CSS properties. As a result, a CSS rule is generated that corresponds to the state of an element.

In this article you will learn how to style a component in React using the emotion CSS-in-JS library

To install Emotion to your React Project

Run this command in your node terminal.

npm i @emotion/styled @emotion/core

How to use emotion with React

Creating a button component with the styled.div style API for creating components from Emotion

A basic code to create a button component in react code

Result:

Button rendered with the styles

Changing based on props

Any interpolations or arguments that are functions in styled are called with props, this allows you to change the styles of a component based on the props.

To add a hover to button

Result:

Button on hover

Using props to distinguish between buttons using different styles

Result

Button style changed based on condition provided with props

When the prop attribute “primary” is used with the Button Component

Result

Button style changed according to the state provided

That’s how you can style with emotion in your React app!

Hope you guys find this useful and start incorporating it in your projects.