0
\$\begingroup\$

I'm using Styled Components for styling and there are many icons defined in the project so in the style file we have this code:

my-component.styles.ts

import { ReactComponent as CloseIcon } from 'svg/close.svg';
import { ReactComponent as OpenIcon } from 'svg/open.svg';
import { ReactComponent as DeleteIcon } from 'svg/delete.svg';
import { ReactComponent as CheckIcon } from 'svg/check.svg';
...

export const StyledCloseIcon = styled(CloseIcon)`
  width: 20px;
  fill: white;
`;

export const StyledOpenIcon = styled(OpenIcon)`
  width: 20px;
  fill: white;
`;

export const StyledDeleteIcon = styled(DeleteIcon)`
  width: 20px;
  fill: white;
`;

export const StyledCheckIcon = styled(CheckIcon)`
  width: 20px;
  fill: white;
`;
...

As it can be seen above, all icons are using the same styling.

And in another component they are used:

import {
  StyledCloseIcon,
  StyledOpenIcon,
  StyledDeleteIcon,
  StyledCheckIcon
} from './my-component.styles';

and then: <StyledCloseIcon />

Is there a way to write it in a shorter way?

\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

You can declare a new variable like "sameStyles"

const sameStyles = `
  width: 20px;
  fill: white;
`;

and pass it in as a template literal expression

export const StyledCloseIcon = styled(CloseIcon)`
  ${sameStyles}
`;

export const StyledOpenIcon = styled(OpenIcon)`
  ${sameStyles}
`;
\$\endgroup\$
2
\$\begingroup\$

Passing the same style value to each different component is anti-pattern. See https://styled-components.com/docs/basics#extending-styles.

You are supposed to have a base component that has base styles. For example,

const Icon = ({ children }) => <div>{ children }</div>;

const StyledIcon = styled(Icon)`
  width: 20px;
  fill: white;
`;

const DeleteIcon = <StyledIcon><DeleteIconSvg/><StyledIcon/>;

export const StyledDeleteIcon = styled(DeleteIcon)`...`;
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.