0

I'm using styled components and I have different elements/icons that require the same styling. What is a way to refactor this if I have separate types of "icons" but with same styling? What is the correct syntax for minimizing repetition in my styled component code?

import React from 'react';
import styled from 'styled-components';
import FolderIcon from 'src/assets/images/folder.svg';
import ListIcon from 'src/assets/images/clipboard.svg';

const StyledIcon = styled.div`
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
`;

const StyledListIcon = styled(ListIcon)`
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
`;

const StyledFolderIcon = styled(FolderIcon)`
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
`;

const MenuItem = (props) => {
    const { label, nodeType, onClick, icon } = props;

    return (
        <MenuItem onClick={onClick}>
            {nodeType === 'LIST' ? (
                <StyledListIcon />
            ) : icon ? (
                <StyledIcon>{icon}</StyledIcon>
            ) : (
                <StyledFolderIcon />
            )}
            <span>{label}</span>
        </MenuItem>
    );
};

export default MenuItem;
jj008
  • 1,033
  • 3
  • 23
  • 48

1 Answers1

1

Thats a use case for css blocks:

const iconStyle = css`
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
`;

const StyledIcon = styled.div`
  ${iconStyle}
`;

const StyledListIcon = styled(ListIcon)`
  ${iconStyle}
`;

const StyledFolderIcon = styled(FolderIcon)`
  ${iconStyle}
`;
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118