DEV Community

Discussion on: How are you using Styled Components?

Collapse
 
nitzanhen profile image
Nitzan Hen

Thanks!! This is really helpful info, and seems like a good pattern.

Just to make sure I understand correctly, a typical component X's styles would be defined in X.style.ts/X.styles.js? And styles in that file would typically be declared using the tag-specific variants (e.g. styled.div, styled.h1)?

Also, based on your experience, is declaring styled-components styles inside the component file (X.tsx) itself a standard practice? Or do most developers use separate files for them (like you do)?

Lastly, do you perhaps have an example repo (yours or anyone else's) following this pattern? I'd love to have one as a point of reference.

Thanks again!

Thread Thread
 
larsejaas profile image
Lars Ejaas

Hi Nitzan

I only have an older repo to share, and honestly I would probably refactor the code a bit today, but feel free to take a look at it at: github.com/LarsEjaas/bruce-willis-app

It's a small page/web app - it's live here at bruce-willis.rocks/en

I am unsure that there is a best practice regarding separating code into separate files or not, but I like to do it this way. We use the same approach in the team where I work.

Let's say I am doing an "awesome button"

Then I would create a folder named AwesomeButton in the components folder.

This would contain:

AwesomeButton.tsx for the functional component,
AwesomeButton.styles.ts for the styles,
AwesomeButton.test.tsx for the tests and maybe
Awesome.stories.tsx if you use storybook.

Furthermore I would make an index.ts file where I would export the functional component like this:

export {default} from AwesomeButton.tsx
Enter fullscreen mode Exit fullscreen mode

This way I can import my AwesomeButton component like this inside my project:

import AwesomeButton from 'components/AwesomeButton'
Enter fullscreen mode Exit fullscreen mode

I think this pattern works well for large projects.

Thread Thread
 
larsejaas profile image
Lars Ejaas

Ahh, missed the part regarding tag-specific variants:

I use both of these:

export const StyledHeadline = styled.h1`
 //...styles
`
Enter fullscreen mode Exit fullscreen mode

and

import UnstyledComponent from 'components/...'

export const StyledComponent = styled(UnstyledComponent)`
  //...styles
`
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
nitzanhen profile image
Nitzan Hen

Thanks a lot for your detailed response!!!
This will be of great help to me.

Thread Thread
 
larsejaas profile image
Lars Ejaas

Ahh, you are welcome! Feel free to drop me a message if something is difficult with Styled Components. It can be a bit difficult at first...