EmotionJS: Style effectively!!
What is Emotion?
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.
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
Result:
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:
Using props to distinguish between buttons using different styles
Result
When the prop attribute “primary” is used with the Button Component
‘
Result
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.