Styling a React app can be challenging, especially if you want to keep your styles organized and maintainable.

To help simplify this process, the Emotion library provides a higher-level abstraction on top of CSS.

What Is Emotion?

Someone typing casually on a laptop next to an open diary and an empty teacup.

Emotion is a library for styling React applications that provides a simple and efficient way to manage your styles.

It allows you to write CSS in JavaScript and provides a flexible API for styling your components.

The Emotion library applies your styles only to the components that use them rather than the entire page.

In JSX, a pragma is a function that transforms the JSX syntax into regular JavaScript.

By default, React uses theReact.createElementfunction as the JSX pragma.

However, with the@jsxImportSourcecomment, you might specify a different pragma.

The button component renders a button with some custom styling.

Here, thecssprop adds the custom styling to the button element.

Thecssprop also supports nested styling.

Nested styling allows you to write styles that are nested within each other.

The background and font color in the code block above will change whenever you hover over the button.

Passing Object Styles to the css Prop

Thecssprop also accepts regular JavaScript object styles.

When styling several components, utilizing object styles allows you to reuse styles in your components.

This is because the styles are defined as JavaScript objects, which use camelCase naming conventions.

To create styled components, you will use thestyledfunction.

Thestyledfunction allows you to create reusable styled components.

To use thestyledfunction, import it from theemotion/styledlibrary.

To get the@emotion/styledlibrary in your utility, you will install it into your project.

you’ve got the option to use this Button in your React program like any other React component.

Like so:

Rendering theAppcomponent will display a button with the styles defined in theButtoncomponent on your screen.

Thestyledfunction also accepts string styles.

It looks different from the object styles approach but functions similarly.