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

Viewed 255

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)

2 Answers

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};
`;

Assuming that your icon components are SVGs, I'd do the following:

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

And then use it as:

<IconWrapper>
  <Icon />
</IconWrapper>
Related