How to add custom styled to a styled component?

Viewed 150

I have a styled component <Icon type="loader"/>. I would like to create another styled component by adding some custom style to this Icon component. I need to pass type to the Icon component how can I achieve this?

const loader = styled(Icon)` font-size:'inherit'`

Directly passing the Icon without any prop works fine.

I have tried this: const CustomIcon = () => <Icon type="loader"/>

const loader = styled(CustomIcon)` font-size:'inherit'`

this gives error.

1 Answers

I think your first way would be sufficient.

const Loader = styled(Icon)`
  font-size: inherit;
`;

You can pass type="loader" to Loader:

<Loader type="loader" />

You can also specify the type prop when you define Loader:

const Loader = styled(Icon).attrs(() => ({
  type: 'loader',
}))`
  font-size: inherit;
`;

Usage:

<Loader /> // type="loader" passed to styled Icon

Demo

Edit how-to-add-custom-styled-to-a-styled-component

Demo code:

const Icon = styled(({ type, ...props }) => {
  switch (type) {
    case "loader":
      return <div {...props} className={props.className + " loader"} />;

    default:
      return <div {...props} />;
  }
})`
  font-size: 3rem;

  &.loader {
    color: red;
  }
`;

const Loader = styled(Icon).attrs(() => ({
  type: "loader"
}))`
  font-size: initial; // overrides Icon fontsize
`;

...

<Icon>Test</Icon>
<Icon type="loader">Test</Icon>
<Loader>Test</Loader>

enter image description here

Related