menu

styled-components

Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress!

Channels
Team

Extending a generic styled component

March 2, 2019 at 4:22am

Extending a generic styled component

March 2, 2019 at 4:22am

Hi all, I know there is a way to extend same components like:

const Button = styled.button`
display: inline-block;
`
const RedButton = styled(Button)`
color: #fff;
`

and there's a way to even use that as a different tag like:

<RedButton as="a" href="/">Click me</RedButton>

but I need a way to create a generic styled component that's not attached to any element and then use it for multiple elements. Something like:

// Typography.js
const Types = styled.default`
margin: 1rem 0;
`
const Heading1 = styled(Types).h1`
font-size: 4.2rem;
`;
const Heading2 = styled(Types).h2`
font-size: 3.6rem;
`;

Is there a way to do this? I can't afford to use as property all the time. I need them all to have their different names


March 12, 2019 at 4:33pm

I believe a style has to have an element, else it wouldn't be a component. Though you could use css which is exported from "styled-components" and create a more generic css with no element bound to it.

const textStyle = css`
margin: 1rem 0;
`

And use this on your text elements.

Edited
like-fill
1
  • reply
  • like

Thanks @elina-a . This looks like the nearest thing to what I wanted

  • reply
  • like