React JS Emotion in CSS
Emotion is a library for CSS-in-JS used with React to style components directly within JavaScript. It provides two main approaches for styling:
- Styled Components: Create styled components using the
styled
function, allowing you to write CSS directly in JavaScript with component-scoped styles. - CSS Function: Use the
css
function to generate style objects that can be applied to elements or components, enabling more flexible and dynamic styling.
Key Features
- Component-Level Styling: Encapsulates styles within components, preventing conflicts.
- Dynamic Styling: Apply styles conditionally based on props and state.
- Theming: Easily define and use themes for consistent styling across the app.
- Performance: Optimized for performance and supports server-side rendering.
Installation
npm install @emotion/react @emotion/styled
# or
yarn add @emotion/react @emotion/styled
Basic Usage
Styled Components:
import styled from '@emotion/styled'; const Button = styled.button` background-color: blue; color: white; padding: 10px; `; function App() { return <Button>Click Me</Button>; }
CSS Function:
import { css } from '@emotion/react'; const style = css` background-color: blue; color: white; padding: 10px; `; function App() { return <button css={style}>Click Me</button>; }
Emotion offers a powerful, flexible way to handle component styling in React applications, providing scoped styles, dynamic styling capabilities, and built-in theming support.