Emotion

website·Indexed 40 days ago

https://emotion.sh/docs/introduction

A library designed for writing css styles with predictability and scalability. It provides a variety of packages including @emotion/react for simple styling in React, @emotion/styled for creating styled components, @emotion/css for framework-agnostic styling, and @emotion/native for React Native. Features include the css prop, theming, server-side rendering via @emotion/server, and a Babel plugin for compile-time optimizations.

Tokens
18.6K
Snippets
123
Records
155
Agent score
73%

What's inside Emotion

  1. Use Object Styles in Emotion

    Emotion allows writing styles as JavaScript objects instead of CSS strings. In this format, CSS properties must be written in camelCase (e.g., backgroundColor instead of background-color). Object styles are natively supported by the css prop and the styled API.
  2. Features of @emotion/babel-plugin

    While Emotion v8+ works without the plugin, @emotion/babel-plugin provides several critical optimizations and features:

    • Components as Selectors: Allows an emotion component to be used as a CSS selector.
    • Minification: Removes leading/trailing spaces in css and styled blocks to reduce bundle size.
    • Dead Code Elimination: Injects /* #__PURE__ */ flags so tools like UglifyJS can remove unused styles.
    • Source Maps: Enables direct navigation to style declarations in JS files (removed in production builds).
    • Contextual Class Names: Includes the variable or component name in the generated class name.
  3. Use @emotion/css for framework-agnostic styling

    @emotion/css is a framework-agnostic version of Emotion. It differs in functionality and API from @emotion/react. It depends on @emotion/cache; custom cache instances can be created using @emotion/css/create-instance.
  4. Style and render cross-platform primitives with @emotion/primitives

    Use @emotion/primitives to create styled components that work across platforms like Web, React Native, and Sketch. It provides a styled API and css function similar to standard Emotion, but targets primitive interfaces. Supported primitives include Text, View, and Image.
    import React from 'react'
    import styled, { css } from '@emotion/primitives'
    import { ThemeProvider } from '@emotion/react'
    
    const theme = {
      color: 'hotpink',
      backgroundColor: 'purple'
    }
    
    // Styled View primitive
    const Container = styled.View`
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 50px;
      border: 5px solid red;
      background-color: ${props => props.theme.backgroundColor};
    `
    
    // Styled Text primitive using object styles
    const Description = styled.Text({
      color: 'hotpink'
    })
    
    // Styled Image primitive
    const Image = styled.Image`
      padding: 40px;
    `
    
    class App extends React.Component {
      render() {
        return (
          <ThemeProvider theme={theme}>
            <Container
              style={css`
                border-radius: 10px;
              `}
            >
              <Description style={{ fontSize: 45, fontWeight: 'bold' }}>
                Emotion Primitives
              </Description>
              <Image
                source={{
                  uri: 'https://cdn.rawgit.com/emotion-js/emotion/main/emotion.png',
                  height: 150,
                  width: 150
                }}
              />
            </Container>
          </ThemeProvider>
        )
      }
    }
  5. Use @emotion/react for React applications

    @emotion/react provides the React-specific implementation of Emotion. It features different APIs and internal logic than the framework-agnostic @emotion/css and depends on @emotion/cache.
  6. Use @emotion/primitives for React Primitives

    @emotion/primitives provides the styled API for React Primitives. Like the native version, its css function returns a React Native style object.
  7. Use @emotion/native for React Native

    @emotion/native provides the styled API for React Native. It includes a css function similar to the web versions, but it returns a React Native style object instead of CSS strings.
  8. Understand @emotion/babel-preset-css-prop features

    This preset enables the css prop project-wide by replacing the default JSX factory. It transforms JSX elements to use Emotion's jsx function instead of React.createElement and automatically adds import { jsx } from '@emotion/react' to files where it is required.
    // Input
    <img src="avatar.png" />
    
    // Output
    jsx('img', { src: 'avatar.png' })
  9. Update styled component generics for Emotion 11

    The styled function's generic parameters have changed. The second ExtraProps parameter is no longer supported. Instead, move the generic props definition to after the styled call.
    // Before (Emotion 10)
    styled<typeof MyComponent, ExtraProps>(MyComponent)({})
    
    // After (Emotion 11)
    styled(MyComponent)<ExtraProps>({})
  10. Install @emotion/primitives

    Install @emotion/primitives using npm or yarn. Note that this package requires react, react-primitives, and prop-types to be installed in your project.
    npm install @emotion/primitives
    # or
    yarn add @emotion/primitives
  11. Apply global CSS styles using the Global component

    Use the Global component from @emotion/react to insert global CSS, such as resets or font faces. The Global component accepts a styles prop, which supports the same values as the css prop (both template literals and object styles). Global styles are automatically removed when the styles change or when the Global component unmounts.
    import { Global, css } from '@emotion/react'
    
    render(
      <div>
        {/* Using template literals */}
        <Global
          styles={css`
            .some-class {
              color: hotpink !important;
            }
          `}
        />
        {/* Using object styles */}
        <Global
          styles={{ '.some-class': { fontSize: 50, textAlign: 'center' } }}
        />
        <div className="some-class">This is hotpink now!</div>
      </div>
    )