Skip to content

"Attrs" constructor - #365

Merged
geelen merged 9 commits into
v2from
attrs
Feb 12, 2017
Merged

geelen merged 9 commits into
v2from
attrs

Conversation

@geelen

@geelen geelen commented Jan 11, 2017 •

Copy link
Copy Markdown
Member

Ok, so this is my proposal for #291, #134 and #184 (and probably others). I think it does what we need in a really nice way:

const X = styled.div.attrs({
  /* add extra props here */
})`
  /* css here as normal */
`

So, @ticky's original code becomes:

const Title = styled.h1.attrs({
  className: 'meow nya'
})`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`

And @ForbesLindesay's becomes:

const activeClassName = btoa(Math.random())
const StyledLink = styled(Link).attrs({
  activeClassName
})`
  color: palevioletred;
  display: block;
  margin: 0.5em 0;
  font-family: Helvetica, Arial, sans-serif;

  &:hover {
    text-decoration: underline;
  }
  &.${activeClassName} {
    color: red;
  }
`

I've added a bit of smarts to make it more similar to how interpolations work:

const Button = styled.button.attrs({
  type: props => props.submit ? 'submit' : 'button'
})`
  /* ... */
`

<Button> //#> <button type="button" class="...">
<Button submit> //#> <button type="submit" class="...">

It gets passed the same { ...this.props, theme } object that interpolations do, and recalculates whenever the CSS snippet gets reevaluated. I.e. it works exactly the same, as much possible.

If you have a prop and an attr with the same key, the prop wins (in that sense they're like defaultProps). That is except for className which just adds everything together. I decided against trying to generalise it—adding extra classes is kind of a special case so I'm happy to keep it that way. If you want any other kind of weird manipulation of properties just make a stateless functional component.

I've also called it attrs because, well, I think props is too overloaded. And, at the end of the day you're rendering HTML elements most of the time. They have attributes, not props. And I see this sort of API most useful when working with these elements—if you have more complex objects you should define a real component. I'm not trying to reinvent React here, but being able to define attributes in the same way you generate and attach CSS turns out to work quite nicely.

The big exception to the previous paragraph is, of course, react-router's Link. It masquerades as a HTML element, but it's a component, so having a single syntax that preserved that facade was important to this. Still, I didn't think it was worth changing the name.

Oh also anything in attrs gets turned into a prop later. That's not very useful, except for some cases like this:

const Image = styled.img.attrs({
  'alt': 'My Beautiful Face'
})`
  &::after {
    content: '${props => props.alt}';
  }
`

Happy to hear feedback, in particular if you can see this breaking down in certain circumstances (that don't just warrant adding an extra component). And everyone's reaction to the name, as well. Don't submit alternate syntaxes here though. That discussion is over at #291, and I'm pretty sure we've considered every possible syntax already. If not, continue the conversation there.

Closes #291, closes #134 and closes #184.

@mxstbr

mxstbr commented Jan 11, 2017

Copy link
Copy Markdown
Member

This is beautiful. Solves all of the concerns with one concise, lovely API! Let's see what everybody else has to say.


I've added a bit of smarts to make it more similar to how interpolations work...

Please tell me that we can reuse that to make props => {} happen in interpolated objects?!

const Box = styled.div`${{
  background: props => props.bg,
}}`

@mxstbr mxstbr modified the milestone: v2.0 Jan 11, 2017
@geelen

geelen commented Jan 11, 2017 •

Copy link
Copy Markdown
Member Author

Oh shit just realised this solves #134 as well!

const Box = styled.div.attrs({
  style: props => ({
    background: `hsl(
      ${props.hue}, 
      ${50 + props.luminosity / 2}%, 
      ${props => props.luminosity}%
    )`
  })
})`
  margin: 2rem auto;
  width: 360px;
  height: 360px;
`

@mxstbr

mxstbr commented Jan 11, 2017

Copy link
Copy Markdown
Member

Holy cow that's huge!

@brunolemos

brunolemos commented Jan 11, 2017 •

Copy link
Copy Markdown
Member

Interesting, I like it.

If it's not already, I suggest being able to pass string literals in the attributes like this:

const ScrollView = styled.ScrollView.attrs({
  contentContainerStyle: `
    background-color: red;
  `,
  style: `
    background-color: green;
  `
})

^ Also, I passed the style attribute, not sure if you handled this case.
I suggest merging the styles from the style attr with the styles from the default way to do it.

@ForbesLindesay

Copy link
Copy Markdown

This is great. The one thought I have is that:

const activeClassName = btoa(Math.random())
const StyledLink = styled(Link).attrs({
  activeClassName
})`
  color: palevioletred;
  display: block;
  margin: 0.5em 0;
  font-family: Helvetica, Arial, sans-serif;

  &:hover {
    text-decoration: underline;
  }
  &.${activeClassName} {
    color: red;
  }
`;

still requires me to think a lot about how the internals work in order to cover this use case. What I'd ideally like to get working is:

const StyledLink = styled(Link).attrs({
  activeClassName: css`
    color: red;
  `
})`
  color: palevioletred;
  display: block;
  margin: 0.5em 0;
  font-family: Helvetica, Arial, sans-serif;

  &:hover {
    text-decoration: underline;
  }
`;

This gives me no need to think about how an active class name gets generated. The only problem I see at the moment is that the return type of css is, I think, the actual string of css, so this would need to somehow know to convert that css into a className.

On an unrelated note, i wonder about calling it withDefaultProps rather than attrs. I think overall we should prioritise clarity over succinctness. A more descriptive name might make it more obvious what it does.

@diegohaz

Copy link
Copy Markdown
Member

@ForbesLindesay For this specific case, I don't think we need that complexity.

const StyledLink = styled(Link).attrs({
  activeClassName: 'active'
})`
  color: palevioletred;
  display: block;
  margin: 0.5em 0;
  font-family: Helvetica, Arial, sans-serif;

  &:hover {
    text-decoration: underline;
  }
  &.active {
    color: red;
  }
`;

It would work perfectly (or am I missing something?)

@diegohaz

diegohaz commented Jan 11, 2017 •

Copy link
Copy Markdown
Member

On an unrelated note, i wonder about calling it withDefaultProps rather than attrs. I think overall we should prioritise clarity over succinctness. A more descriptive name might make it more obvious what it does.

Yeah, it seems too much like React's defaultProps. I didn't read everything yet, but the only difference I see is we are passing in actual props here (so you can set a prop based on actual props).

I'm afraid it stimulates people to use this instead of defaultProps, which should be used for most cases. The image alt case, for example, should use defaultProps instead of attrs, from my point of view.

const Image = styled.img`
  &::after {
    content: '${props => props.alt}';
  }
`

Image.defaultProps = {
  alt: 'My Beautiful Face'
}

@ForbesLindesay

Copy link
Copy Markdown

For this specific case, I don't think we need that complexity.

The advantage of my proposal is that it doesn't require me to know the internal structure of the Link component. If I use &.active { color: red; }, I need to know that the activeClassName gets applied to the same element as the normal className.

If I can somehow tell styled-components to generate another, totally separate style, it doesn't matter what the internal structure is.

I'm not currently sure if this is worth trying to change/extend the API for though. I may need to keep thinking about it/try out the existing API.

I'm afraid it stimulates people to use this instead of defaultProps

I'm not sure if this is actually a problem. Is there anything wrong with doing:

const Image = styled.img.withDefaultProps({
  alt: 'My Beautiful Face',
})`
  &::after {
    content: '${props => props.alt}';
  }
`

ticky added a commit to buildkite/frontend that referenced this pull request Jan 11, 2017
@ticky

ticky commented Jan 11, 2017

Copy link
Copy Markdown

Nice!!! Just had a play, this feels much, much cleaner!

@diegohaz

diegohaz commented Jan 11, 2017 •

Copy link
Copy Markdown
Member

The advantage of my proposal is that it doesn't require me to know the internal structure of the Link component. If I use &.active { color: red; }, I need to know that the activeClassName gets applied to the same element as the normal className.

If this is a problem, it's Link's responsibility, not ours. This is how react-router works.

I'm not sure if this is actually a problem.

What's the benefit of using a different API from another library (styled-components) if it does exactly the same as React's defaultProps? There're also some libraries that counts on that, such as react-docgen. I think we should not encourage it.

Actually, besides className and cases when you want to set the attribute based on props (like the submit example), I don't think .attrs should be used. Even the Link example should use React's defaultProps.

Just my 2c.

@geelen

geelen commented Jan 11, 2017

Copy link
Copy Markdown
Member Author

Thanks for the discussion and the feedback. withDefaultProps is not a bad name, but it doesn't actually work the way defaultProps works—these are reevaluated every time props changes, and they can take functions. It's also kind of a react-specific name. Styled Components is wholly tied to React at the moment but only by implementation, not by design.

As for the Link discussion, I tend to agree with @diegohaz that it's part of Link's API that it applies activeClassName in certain cases. I don't think it makes much sense to add css-generation-and-injection behaviour into the attrs API, they just feel like totally separate concerns.

However, I could consider treating css blocks specially:

/* React Native example */
const ScrollView = styled.ScrollView.attrs({
  contentContainerStyle: css`
    background-color: red;
  `
})`
    background-color: green;
`

/* inline style example */
const Box = styled.div.attrs({
  style: css`
    background: hsl(
      ${props => props.hue}, 
      ${props => 50 + props.luminosity / 2}%, 
      ${props => props.luminosity}%
    );
  `
})`
  margin: 2rem auto;
  width: 360px;
  height: 360px;
`

This would basically convert CSS snippets to objects, so no nesting or anything would be permitted, but it might be useful for these cases. Feels like this would be useful for #149 too.

@geelen

geelen commented Jan 12, 2017

Copy link
Copy Markdown
Member Author

Ok so that previous comment isn't going to work just yet. It ends up needing to do something really similar to css-to-react-native which at the moment depends on PostCSS, and we're just about to replace PostCSS with Stylis (#286).

I've opened #371 to track it. But otherwise I think we should merge this.

@kidwm

kidwm commented Feb 9, 2017

Copy link
Copy Markdown

will this feature be in v2?

@mxstbr

mxstbr commented Feb 11, 2017

Copy link
Copy Markdown
Member

@kidwm yes.

@bondz

bondz commented Feb 17, 2017

Copy link
Copy Markdown

This should be available in [email protected] right? I'm getting _styledComponents2.default(...).attr is not a function

@mxstbr

mxstbr commented Feb 17, 2017

Copy link
Copy Markdown
Member

That's because @geelen forgot to export it 😉 PR?

@bondz

bondz commented Feb 17, 2017

Copy link
Copy Markdown

Oh, yes. 😀

@bondz bondz mentioned this pull request Feb 17, 2017
@mxstbr

mxstbr commented Feb 17, 2017

Copy link
Copy Markdown
Member

Wait sorry that's not right, this is working as intended. What's the code you're running?

@bondz

bondz commented Feb 17, 2017

Copy link
Copy Markdown

@mxstbr that's weird, tried it in webpackbin now and it works. It was webpack using the old cache in my build, works now. Thanks.

@bondz

bondz commented Feb 17, 2017

Copy link
Copy Markdown

@bondz

bondz commented Feb 17, 2017

Copy link
Copy Markdown

@k15a

k15a commented Feb 17, 2017

Copy link
Copy Markdown
Member

Yeah I've noticed that I looked wrong that's why I've removed my comment :p

@geelen

geelen commented Feb 18, 2017

Copy link
Copy Markdown
Member Author

Not sure what the problem is here but attrs shouldn't be being attached to the styled component itself—it's part of the constructor, not the component, so being attached here is correct.

@streamich

streamich commented Feb 22, 2018 •

Copy link
Copy Markdown

@geelen Can it be done like this?

const Button = styled(({className, submit}) =>
  <input className={className} type={submit ? 'submit' : 'button'} />
)`
  /* ... */
`

@kitten

kitten commented Feb 22, 2018

Copy link
Copy Markdown
Member

@streamich this certainly works, but please don't comment on stale PRs and issues. Especially since this is a PR and you have a rather unrelated question. I don't mean to be rude, so my suggestion is to go to Spectrum, or Twitter, or at the last create an issue for your questions 😉

@styled-components styled-components locked as resolved and limited conversation to collaborators Feb 22, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.