1

Not a fan of duplicating code I've been researching for a way to build a component that I can pass header elements and then call upon it in my site (somewhat of a site default I guess you could say). In my theme folder I've created my index.js with set colors, sizes, etc. etc and created a GlobalStyles.js with my components, for example:

export const H1 = styled.h1`
  font-family: 'Open Sans';
  color: ${({ theme }) => theme.colors.color03};
  font-size: ${({ theme }) => theme.desktopSizes.h1};
  @media only screen and (max-width: ${({ theme }) => theme.breakpoints.md}) {
    font-size: ${({ theme }) => theme.mobileSizes.h1};
  }
`

export const H2 = styled.h2`
  font-family: 'Open Sans';
  color: ${({ theme }) => theme.colors.color03};
  font-size: ${({ theme }) => theme.desktopSizes.h2};
  @media only screen and (max-width: ${({ theme }) => theme.breakpoints.md}) {
    font-size: ${({ theme }) => theme.mobileSizes.h2};
  }
`

and this goes on all the way to the h5 element. Usage would be in src calling upon it with a typical:

// Master Styled Components
import { H1, H2 } from '../../theme/GlobalStyles'

usage:

<H1>Header 1</H1>
<H2>Header 2</H2>

and if I wanted to modify or add to it I'm aware of:

const H1 = styled(H1)`
 // code
`

when I tried to write this out I realized that if I wanted to pass it to a main Header component that, from my research in the docs, the element would need to be passed, example:

const Header = styled.element`
  font-family: 'Open Sans';
  color: ${({ theme }) => theme.colors.color03};
`

then I was going to do:

export const H1 = styled(Header)`
  font-size: ${({ theme }) => theme.desktopSizes.h1};
  @media only screen and (max-width: ${({ theme }) => theme.breakpoints.md}) {
    font-size: ${({ theme }) => theme.mobileSizes.h1};
  }
`

but dont think that would work from my research and other areas of searching I've read:

In Styled Components is there a way to implement D.R.Y. when building a header component that only has a changing theme size?

DᴀʀᴛʜVᴀᴅᴇʀ
  • 7,681
  • 17
  • 73
  • 127

0 Answers0