1
\$\begingroup\$

I'm creating a versatile component with styled-components that essentially just maps style attributes. I feel my type declarations seem inefficient in getting access to props.

Is it appropriate to use the props interface for each of these styles the way I'm doing it? Thoughts?

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

import { elevation as boxShadow, color } from '../../StyleBase';
import { mapStyle } from '../../StyleBase';

export interface BoxProps {
    fill?: boolean;
    background?: string;
    padding?:
        | number
        | [number, number]
        | [number, number, number]
        | [number, number, number, number];
    margin?:
        | number
        | [number, number]
        | [number, number, number]
        | [number, number, number, number];
    radius?: number;
    elevation?: number;
    border?: boolean;
}

const padding = ({ padding }: BoxProps) => mapStyle('padding', padding);

const margin = ({ margin }: BoxProps) => mapStyle('margin', margin);

const radius = ({ radius }: BoxProps) => mapStyle('border-radius', radius);

const background = ({ background }: BoxProps) =>
    mapStyle('background', background);

const elevation = ({ elevation }: BoxProps) =>
    elevation && mapStyle('box-shadow', boxShadow[elevation]);

const fill = ({ fill }: BoxProps) =>
    fill &&
    css`
        flex: 1 1 0%;
    `;

const border = ({ border }: BoxProps) =>
    border &&
    css`
        border: 1px solid ${darken(0.07, color.GRAY_LIGHT)};
    `;

export const Box = styled.div`
  ${fill}
  ${padding}
  ${margin}
  ${radius}
  ${background}
  ${elevation}
  ${border}
`;
```
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.