DEV Community

Discussion on: How are you using Styled Components?

Collapse
 
nitzanhen profile image
Nitzan Hen

My implementation, in a simple example, goes something like this:

import React from 'react';
import styled from 'styled-components'; // 1. Import styled-components

const AComponentStyled = styled(AComponent)`` // 2. Create styled variant

function AComponent({ className }) { // 3. Receive className prop

  //...

  return (
    // 4. Pass className prop to JSX root
    <div className={className} /> 
  )
} 

export default AComponentStyled; // 5. Export styled variant
Enter fullscreen mode Exit fullscreen mode

Of course, the CLI generalizes this example to any component, and supports Typescript, using a named export (instead of the default export), etc.

Most examples out there used the component-specific variants, such as styled.h1, but to me it felt that the more generic styled(component) are more useful - however if you are using the component-specific variants, do tell!

Collapse
 
bcheidemann profile image
Ben Heidemann

I use component specific variants quite regularly. Generally, as long as it's a simple component consisting of a single styled element (e.g. a div) I will use the component specific variants as I find them easier to read. However, I work a lot with Material UI and when styling MUI components I use styled(MuiComponent). Do you use the styled(Component) syntax you describe above for consistency or is there another reason?

Collapse
 
nitzanhen profile image
Nitzan Hen

This makes a lot sense!

I actually have used Material UI a lot as well, and I think I originally tended towards the generic styled(Component) syntax simply because I was used to MUI's way of doing things - where the definition of the styles for a component is closely tied to the component itself (at least that's how it was when MUI still used JSS).

However, I'm realizing more and more how useful and neat the tag-specific variants are! Cheers!