best practices to reduce duplicated style in styled-components

Viewed 694

I want to write DRY (Donot Repeat Yourself) code with styled-component.

I know best way to be DRY with styled-component is like below,

cost fontSize = '18px';
const StyledComponent = styled(Component)`
    font-size: ${fontSize};
`;
const StyledCompoentA = styled(StyledComponent)`
    background-color: red;
`;
const StyledCompoentA = styled(StyledComponent)`
    background-color: blue;
`;

However I don't know how to apply this on below code,

import styled from 'styled-components';
import { MenuUnfoldOutlined, MenuFoldOutlined } from '@ant-design/icons';

const StyledMenuUnfoldOutlined = styled(MenuUnfoldOutlined)`
    font-size: 18px;
    line-height: 64px;
    padding: 0 24px;
    cursor: pointer;
    transition: color 0.3s;

    &:hover {
        color: #1890ff;
    }
`;

const StyledMenufoldOutlined = styled(MenuFoldOutlined)`
    font-size: 18px;
    line-height: 64px;
    padding: 0 24px;
    cursor: pointer;
    transition: color 0.3s;

    &:hover {
        color: #1890ff;
    }
`;

Is there a better way to reduce duplicated styles?

1 Answers

I found one way to solve duplicated style.

According to styled-components API references, there is a way to create partial css.

import styled, { css } from 'styled-components';

const menuStyle = css`
    font-size: 18px;
    line-height: 64px;
    padding: 0 24px;
    cursor: pointer;
    transition: color 0.3s;

    &:hover {
        color: #1890ff;
    }
`;

const StyledMenuUnfoldOutlined = styled(MenuUnfoldOutlined)`
    ${menuStyle}
`;

const StyledMenufoldOutlined = styled(MenuFoldOutlined)`
    ${menuStyle}
`;

The problem of css is it requires Babel plugin.

Related