r/reactjs • • Sep 05 '18

Tutorial Announcing styled-components v4: Better, Faster, Stronger

https://medium.com/styled-components/announcing-styled-components-v4-better-faster-stronger-3fe1aba1a112
203 Upvotes

80 comments sorted by

View all comments

Show parent comment

1

u/yardeni Sep 06 '18

I don't see it that way. Naming elements is actually helpful in my experience. Makes JSX much more readable, and forces you to really figure out what function each element is there for.

Also, you do need to name classes, it's really not that different.

1

u/enkideridu Sep 07 '18 edited Sep 07 '18

Naming elements can be helpful, but not every element that needs a style is worth naming. With emotion, you don't have to create styled-components or add classNames to style components/elements, you still can when you think it makes sense, but you get to choose where to draw the line

Imagine if you had this:

const Foo = (props) =>
  <div {...props}>
    <SomeWidget />
    <AnotherWidget />
  </div>

And you wanted to

  • add some padding to the container of Foo
  • add some additinal whitespace to the left of AnotherWidget

With styled components, you'd have to do

const Container = styled('div')`
  padding: 20px;
`;

const AnotherWidgetWithSomeStyles = styled(AnotherWidget)`
  padding-left: 20px;
`

const Foo = (props) =>
  <Container {...props}>
    <SomeWidget />
    <AnotherWidgetWithSomeStyles />
  </Container>

Or maybe you could add a className on, like <AnotherWidget className="add-space-to-the-left" /> and select it in container. Either way, you'd have to either expend some brainpower to think up a nice fitting name, or, more likely, live with a bunch of poorly named components &&|| classNames

With emotion, you have the option to inline like this:

const Foo = (props) =>
  <div css={`padding: 20px`} {...props}>
    <SomeWidget />
    <AnotherWidget css={`padding-left: 20;`}/>
  </div>

For larger pieces of styles, sure break it out of the jsx into its own variable. If it's going to be used in a few places, make it into a styled component. For all the nibbly bits that just need a line or two of CSS, you don't have to suffer premature naming.

1

u/yardeni Sep 07 '18

You could also inline style when it's such a small change. Or create a Div element that creates different css based on props. That being said, I do see your point and would consider giving emotion a shot, if I didn't currently work on react native haha.

In the end I'm just thankful that we have such a good toolset to choose from.