title |
---|
Introduction |
Emotion is a lightweight library designed for writing styles in JavaScript, enabling powerful and predictable style composition using both string and object styles. It also provides a great developer experience with features such as source maps, labels, and testing utilities.
There are two primary methods of using Emotion. The first is framework agnostic and the second is for use with React.
npm i emotion
The "emotion" package is framework agnostic and the simplest way to use Emotion.
-
Requires no additional setup, babel plugin, or other config changes.
-
Works in situations where configuration is restricted or not possible such as with Create React App
-
The
css
prop is not used or needed. -
You simply prefer to use the
css
function to generate class names andcx
to compose them.
// @live
import { css, cx } from 'emotion'
const color = 'darkgreen'
render(
<div
className={css`
background-color: hotpink;
&:hover {
color: ${color};
}
`}
>
This has a hotpink background.
</div>
)
npm i @emotion/core
The "@emotion/core" package requires React and is recommended for users of that framework if possible.\
-
Best when using React with a build environment that can be configured.
-
Server side rendering with zero configuration.
-
Theming works out of the box.
-
CSS prop support which removes boilerplate when composing components styled with emotion.
-
ESlint plugins available to ensure proper patterns and configuration are set.
// @live
// this comment tells babel to convert jsx to calls to a function called jsx instead of React.createElement
/** @jsx jsx */
import { css, jsx } from '@emotion/core'
const color = 'darkgreen'
render(
<div
css={css`
background-color: hotpink;
&:hover {
color: ${color};
}
`}
>
This has a hotpink background.
</div>
)
npm i @emotion/styled
The @emotion/styled package is for those who prefer to use the styled.div
style API for creating components.
// @live
import styled from '@emotion/styled'
const Button = styled.button`
color: turquoise;
`
render(<Button>This my button component.</Button>)