Changing Tag Type When Extending Component in Styled-Components

Viewed 1300

I have a Styled-Component called Headline that I wish to extend with another component called SubHeadline. Now, Headline looks like this:

const Headline = styled.h2`
// Css styles go here
`

What I would like to do is to both extend the styles of Headline AND change the tag type to something else (say h3). Something like this:

const SubHeadline = styled(Headline).h3`
// Css styles go here
`

Now the above does NOT work, but it illustrates what I would like to do.

Any ideas on how to do this?

1 Answers

The way I know how to manage this is described in this Github Issue. Put all your functionality out in variables and added it to your different child components:

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

const HeadlineStyles = css`
  // Css for Headline here
`

const Headline = styled.h2`
  ${HeadlineStyles}
`

const SubHeadline = styled.h3`
  ${HeadlineStyles}
`
Related