Search code examples
cssreactjsstyled-componentsemotion

Styled compoenents/emotion: add a style object to apply to different components


I create different icons in Emotion (could be Styled Components as well), and I apply the exact styling to each icon:

const BellIcon = styled(Bell)`
  width: ${(props) => props.theme.sizes.iconDimension};
  height: ${(props) => props.theme.sizes.iconDimension};
  flex-shrink: 0;
`;

const PlayIcon = styled(Play)`
  width: ${(props) => props.theme.sizes.iconDimension};
  height: ${(props) => props.theme.sizes.iconDimension};
  flex-shrink: 0;
`;

const RefreshIcon = styled(Refresh)`
  width: ${(props) => props.theme.sizes.iconDimension};
  height: ${(props) => props.theme.sizes.iconDimension};
  flex-shrink: 0;
`;

Is there a way to to outsource the styling into an object and apply the same styles to each icon using the object? (or another method? Just so the code isn't repetitive)


Solution

  • You can utilize the "css" function from "styled-components" to group styles in an object.

    Like this:

    import { css } from 'styled-components';
    
    const GroupedStyles = css`
      width: ${(props) => props.theme.sizes.iconDimension};
      height: ${(props) => props.theme.sizes.iconDimension};
      flex-shrink: 0;
    `;
    
    const RefreshIcon = styled(Refresh)`
      ${GroupedStyles};
    `;
    
    const PlayIcon = styled(Play)`
      ${GroupedStyles};
    `;