CSS-in-JS examples, using Emotion library
A lot of research has been done to select the most robust css-in-js library, and we eventually chose Emotion.
After more than a year working with it at a production-grade level, we haven't noticed any drawbacks.
Emotion allows to use both the
After more than a year working with it at a production-grade level, we haven't noticed any drawbacks.
Emotion allows to use both the
styled component
and JSX-like ways of writing your CSS styles, as showcased below.Our personal preference is to use JSX-like way of writing styles, instead of the Styled Components approach.
We want to make it clear that such choice is personal, and we have selected on purpose Emotion, because it allows both.
In our opinion, the JSX way is better for iterating quickly when you don't know exactly the shape of your components.
The choice is yours, do as you like!
We want to make it clear that such choice is personal, and we have selected on purpose Emotion, because it allows both.
In our opinion, the JSX way is better for iterating quickly when you don't know exactly the shape of your components.
The choice is yours, do as you like!
The below example uses the JSX way, with CSS written directly in the element.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { css } from '@emotion/core';
<div
css={css`
# Those rules apply to the top-level element (the "div")
justify-content: center;
text-align: center;
margin-left: auto;
margin-right: auto;
# Those rules apply to children elements using the "child-class" css class
.child-class {
margin: auto;
width: 50%;
@media screen and (min-width: 576px) {
margin: 50px
}
}
`}
>
Top-level content
<p className={'child-class'}>Child content</p>
</div>
The below example uses the Styled Component way, with CSS written in a dedicated React Component.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import styled from '@emotion/styled';
const StyledImage = styled.img`
width: 50px;
height: 100px;
@media screen and (min-width: 576px) {
height: 50px
}
`;
const Image = (props): JSX.Element => {
const { onClick } = props;
return (
<StyledImage onClick={onClick}
);