How To Make A List Component With Emotion
A comprehensive guide to creating styled list components using Emotion, the powerful CSS-in-JS library for React applications
Emotion is a powerful CSS-in-JS library that transforms how developers approach component styling in React applications. By enabling developers to write CSS directly within JavaScript, Emotion bridges the gap between traditional styling approaches and modern component-based architecture. The library's intuitive API allows for rapid development of styled components while maintaining excellent performance and developer experience.
The primary advantage of using Emotion lies in its ability to associate styles directly with components, ensuring that styling remains scoped and doesn't conflict across different parts of an application. This approach eliminates common issues like global CSS pollution and selector collisions that plague traditional stylesheet-based approaches. As React applications grow in complexity, maintaining clean and manageable styling becomes increasingly important, and Emotion provides the tools necessary to achieve this goal.
For teams building React applications, adopting Emotion represents a significant step toward more maintainable and scalable frontend architectures. The library supports both template literal syntax and object styles, giving developers the flexibility to choose the approach that best fits their project's requirements. Our web development services team leverages modern styling solutions like Emotion to deliver professional React applications that scale efficiently. Additionally, Emotion's integration with TypeScript provides enhanced type safety and improved developer experience through intelligent autocomplete and compile-time error detection.
Installation and Setup
Install and configure Emotion in React projects with proper package selection
Creating List Components
Build ordered and unordered lists using the styled API with custom styling
Dynamic Styling
Apply conditional formatting based on props and component state
Theme Integration
Implement consistent styling through theming across all components
Getting Started with Emotion
Installation and Setup
Setting up Emotion in a React project requires installing the appropriate packages based on your project's needs. The primary packages are @emotion/react and @emotion/styled, each serving a distinct purpose in the styling workflow. The @emotion/react package provides the core functionality including the css prop and theming capabilities, while @emotion/styled offers the styled API for creating styled components. This two-package approach provides maximum flexibility for different styling preferences and use cases.
For most React projects, installing both packages provides the most comprehensive set of tools for building styled components efficiently. The installation process also includes optional dependencies that enhance the development experience. For TypeScript projects, the built-in type definitions provide excellent type safety without additional configuration.
Configuration requirements vary based on the build tool being used. Webpack and Vite projects generally work without additional configuration, while some environments may require the Emotion babel plugin for optimal performance. This plugin enables automatic label generation and improves CSS class name readability during development.
1npm install @emotion/react @emotion/styledUnderstanding the Two APIs
Emotion provides two primary APIs for styling React components, each suited to different use cases and developer preferences. The @emotion/styled API allows developers to create styled components using a syntax that closely resembles CSS, using template literals to define styles. This approach is particularly appealing to developers coming from traditional CSS backgrounds, as it maintains familiar syntax while providing the benefits of CSS-in-JS.
The @emotion/react API offers a different approach through the css prop, which can be applied directly to any React element. This method integrates styling directly into JSX, allowing for more granular control over individual elements within a component. The css prop approach excels in situations where styles need to be applied dynamically or conditionally based on component state.
Both APIs share the same underlying styling capabilities and can be mixed within the same project. Many teams choose one approach as their primary method while using the other for specific use cases where its strengths are most valuable. Understanding both APIs enables developers to make informed decisions about which approach best fits each unique situation within their application.
Creating Your First List Component
1import styled from '@emotion/styled';2 3const OrderedList = styled('ol')`4 font-size: 16px;5 margin-left: 2rem;6 list-style-type: decimal;7 padding-left: 0;8`;9 10const UnorderedList = styled('ul')`11 font-size: 16px;12 margin-left: 2rem;13 list-style-type: disc;14 padding-left: 0;15`;16 17const ListItem = styled('li')`18 font-size: 14px;19 line-height: 1.6;20 margin-bottom: 0.5rem;21`;Creating list components with Emotion follows the same patterns used for other styled elements. Using the styled API, developers can create custom list components that encapsulate both structure and presentation. This approach promotes reusability and ensures consistent styling throughout the application.
These styled components can then be used in JSX just like any other React component, providing a clean and intuitive API for building list-based interfaces. By encapsulating both structure and presentation, Emotion list components promote code reuse and maintain consistency throughout your application.
Customizing List Appearance
1const ColoredList = styled('ul')`2 font-size: 16px;3 list-style-type: none;4 padding-left: 0;5 6 li {7 color: #333;8 padding: 8px 16px;9 border-left: 3px solid #0066cc;10 background-color: #f8f9fa;11 margin-bottom: 8px;12 13 &:hover {14 background-color: #e9ecef;15 border-left-color: #004494;16 }17 }18`;Dynamic Styling with Props
1const StyledList = styled('ul')`2 font-size: ${props => props.size === 'large' ? '18px' : '14px'};3 list-style-type: ${props => props.ordered ? 'decimal' : 'disc'};4 padding-left: ${props => props.indented ? '2rem' : '1rem'};5 6 li {7 color: ${props => props.colorScheme === 'dark' ? '#fff' : '#333'};8 background-color: ${props => props.highlighted ? '#fff3cd' : 'transparent'};9 }10`;Theme Integration
Emotion's theming capabilities provide a powerful mechanism for maintaining consistent styling across all list components within an application. By defining a theme object that contains design tokens such as colors, spacing values, and typography settings, developers ensure that lists and other components adhere to the established design system.
The theme is passed to components through Emotion's ThemeProvider, which makes the theme object available to all styled components within its scope. This approach promotes consistency and makes it easy to implement global style changes. When design updates are required, developers need only modify the theme object rather than updating each individual component.
Using themes promotes consistency and makes it easy to implement global style changes. When design updates are required, developers need only modify the theme object rather than updating each individual component. This approach significantly reduces maintenance overhead in larger applications.
1import { ThemeProvider } from '@emotion/react';2 3const theme = {4 colors: {5 primary: '#0066cc',6 secondary: '#6c757d',7 success: '#28a745'8 },9 spacing: {10 small: '0.5rem',11 medium: '1rem',12 large: '1.5rem'13 }14};15 16const ThemedList = styled('ul')`17 font-size: ${props => props.theme.typography.fontSize.base};18 color: ${props => props.theme.colors.text};19 20 li {21 padding: ${props => props.theme.spacing.small};22 border-left: 2px solid ${props => props.theme.colors.primary};23 }24`;Best Practices for Emotion Lists
TypeScript and Object Styles
Using TypeScript with Emotion provides significant advantages for list component development, including compile-time error detection, improved IDE support, and better documentation through type annotations. TypeScript's type inference automatically detects styled component props and return types, providing helpful autocomplete suggestions during development.
For teams working on complex React applications, combining Emotion with proper web development practices creates a robust styling workflow that catches errors at compile time rather than runtime. The TypeScript compiler validates that only valid CSS properties and values are used, catching typos and incorrect values before runtime. This validation becomes increasingly valuable as applications grow in size and complexity. Object styles also enable easier composition of styles from shared constants, making it simpler to implement design system tokens consistently.
1import styled from '@emotion/styled';2 3interface ListProps {4 variant?: 'primary' | 'secondary';5 spacing?: 'compact' | 'comfortable';6}7 8const StyledList = styled.ul<ListProps>({9 fontSize: '16px',10 listStyleType: 'none',11 paddingLeft: 0,12}, props => ({13 marginLeft: props.spacing === 'compact' ? '1rem' : '2rem',14 backgroundColor: props.variant === 'primary' ? '#f8f9fa' : 'transparent'15}));Colocating Styles with Components
One of Emotion's core strengths is the ability to colocate styles with the components they style, improving code organization and maintainability. Rather than maintaining separate stylesheet files, styled definitions exist alongside their corresponding components, making it easier to understand and modify both together.
For list components, this approach means defining all related styled components in the same file as the component that uses them. This colocation pattern provides several benefits: easier refactoring as related code is grouped together, clearer ownership of both component and styling logic, and reduced context switching when making changes.
New developers to a project can more quickly understand component behavior when all relevant code resides in a single location. This approach is particularly valuable for teams working on large-scale applications where maintaining consistency across hundreds of components is essential for long-term maintainability.
Performance Considerations
Understanding Emotion's performance characteristics helps developers make informed decisions about when and how to use the library. Emotion generates CSS at runtime and injects it into the document head, which differs from build-time solutions but offers significant flexibility in return.
For list components, several practices help optimize performance: using the css prop for dynamic styles, memoizing complex selectors, and avoiding inline styles for static values. For applications rendering large numbers of list items, virtualized list implementations often provide better performance than rendering hundreds of individual list item components.
Emotion can be combined with virtualization libraries and AI-powered automation solutions to create performant lists even with substantial data sets. This combination allows teams to maintain the developer experience benefits of Emotion while still achieving the performance characteristics needed for data-intensive applications.
Advanced Patterns
1const BaseList = styled.ul`2 list-style-type: none;3 padding: 0;4 margin: 1rem 0;5`;6 7const BaseItem = styled.li`8 padding: 0.75rem 1rem;9 border-bottom: 1px solid #e9ecef;10`;11 12const CardList = styled(BaseList)`13 background-color: #fff;14 border-radius: 8px;15 box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);16 17 ${BaseItem} {18 padding: 1rem 1.25rem;19 &:hover {20 background-color: #f8f9fa;21 }22 }23`;Responsive List Design
Modern applications require list components that adapt gracefully to different screen sizes and device capabilities. Emotion supports responsive styling through CSS media queries and prop-based styling that responds to viewport dimensions. This flexibility ensures your lists look great on mobile phones, tablets, and desktop computers alike.
For more complex responsive behavior, developers can use custom hooks or context to detect viewport size and pass appropriate props to styled components. This approach allows for truly adaptive list components that can transform their layout and appearance based on the device viewing them.
1const ResponsiveList = styled.ul`2 list-style-type: none;3 padding: 0;4 margin: 0;5 6 @media (min-width: 768px) {7 display: grid;8 grid-template-columns: repeat(2, 1fr);9 gap: 1rem;10 }11 12 @media (min-width: 1200px) {13 grid-template-columns: repeat(3, 1fr);14 }15`;Conclusion
Creating list components with Emotion provides a powerful approach to styling in React applications that combines the flexibility of CSS with the component model of React. Through careful application of the patterns and practices outlined in this guide, developers can create list components that are visually appealing, performant, and maintainable.
The key benefits of using Emotion for list components include scoped styling that prevents conflicts, dynamic styling capabilities through props, excellent TypeScript support, and the ability to colocate styles with components. These advantages make Emotion an excellent choice for projects of any size, from small prototypes to large-scale enterprise applications.
As with any tool, the most effective use of Emotion comes from understanding its strengths and applying its capabilities appropriately to your specific use cases. The patterns demonstrated here provide a foundation that can be adapted and extended to meet the unique requirements of any project. Whether you're building a simple navigation menu or a complex data display component, Emotion provides the flexibility and power needed to create professional-grade list components that scale with your application's needs.
Sources
- Emotion.sh - Styled Components - Official documentation for the styled API
- Emotion.sh - Best Practices - Official best practices guide
- GeeksforGeeks - List Component with Emotion - Practical examples for list components
- DigitalOcean - How To Use Emotion for Styling in React - Getting started with Emotion in React