Repository navigation
Transient props - #2093
Transient props#2093quantizor wants to merge 5 commits into
Conversation
This commit introduces a new JSX concept called "transient props". When a prop is prefixed with a $ (e.g. $foo), it will only be applied to the immediate component and not forwarded to any deeper children or layers of the component stack. In the case of styled-components, this equates to a styling-only prop that you may consume in your style interpolations but will never end up on the DOM node or in your wrapped component. Other props can still be accessed normally.
|
This could also potentially land in v4.x but without the existing prop validation being removed. If it catches on we can deprecate prop validation and remove it in v5. |
|
It is a JSX concept coming from react? Or just a styled-components JSX concept? |
|
Just a styled-component's thing; the only props that have any special meaning in JSX are |
|
Can I make a request? Why not |
|
Is the And is there still a chance you'll also implement a static "prop-filtering at component definition time" solution similar to what's described here, for people like me who really don't want to expose styled-component-specific props in their UI components? (For example like this: ) On a side-note, the |
|
There are a lot of linter rules around use of _ and personally I just prefer how $ looks. It’s a bit easier to write imo.
|
|
💯 Still a big fan of this ❤️ |
We can definitely look into that. That particular change would have to be in v5 if we do land it. |
|
Just realised a downside to this approach: it makes the abstraction leaky by making styled-components very different from normal React component. That in turn makes it hard to evolve that component without breaking changes to any user of the component. To elaborate, imagine a Button component with a primary property. At first, your implementation would probably be something like this: export const Button = styled.button``;So throughout the whole application you use the Button like so: <Button $primary disabled />Now imagine you get some new requirements and your Button needs some custom behaviour, so you change the implementation to something like this: const StyledButton = styled.button``;
export const Button = (props) => (
<StyledButton>{/* ... */}</StyledButton>
)Now you're stuck in a bad place since you have only got these two options:
That sucks. 😕 I'm leaning towards the "style-prop" approach (a single blacklisted prop that's always filtered and everything else is passed through), specifically a prop that doesn't have any s-c specific connotation (I like |
It's a choice to be made by the developer. If they need multiple layers of components to receive the prop, they should not mark it as transient and just filter it out at the appropriate level so it doesn't hit the DOM. |
|
Hint: Maybe this whole dance around custom props wouldn't be a problem if you
You're probably as tired of hearing me repeat this as I am repeating it, but I'll do it once more: To me it is SO obvious that both custom prop and prefixed prop solutions are hacky workarounds around the fact that developers HAVE to manage (i.e. decide whether to pass on or not) their component's props at some point. I much prefer doing this once when I write the component over doing/thinking about it EVERY SINGLE TIME I use the component: "Wait, is this component a styled component? Is this prop an s-c-exclusive styling prop? Guess I have to go and look it up..." What @mxstbr says above hits the nail on the head even though I don't agree with his conclusion because nesting a prop especially for s-c isn't all that different from giving it a prefix. React devs are used to some boilerplate ( ✋ 🎤 |
A big part of what makes styled-components so nice in my mind is that it's "Just React Components™️". I would not want to require users to choose upfront whether they'll ever have more complex requirements—those are always changing, so I think they'd end up always having to wrap each styled component they export, which is not great.
That would be the case if the prop was called "sc" or something like that, but not if giving it a generic name like |
Sure, every component can have a So I'd still be one of those who'd
|
|
I agree with @diondiondion. The default, standard way of passing props to a component is passing them directly, not as a nested object like I'd much prefer to leave props as is, and, instead, add a native SC way for users to blacklist props in the component definition that shouldn't end up in the dom. Imo, the problems with
|
Easiest solution for now, until we get transient props [1]. [1] styled-components/styled-components#2093
…#404) Easiest solution for now, until we get transient props [1]. [1] styled-components/styled-components#2093
|
I'm in agreement with @diondiondion's previous comment. I guess I'm lost on why it's clumsy to handle it at the component definition level. Is there really a situation where you might want to pass a prop sometimes but other times not? That sounds like an implementation issue. But as long as customization exists via |
|
Recently I just found that using Everything is ok, no extra props, no additional layers, no extra mechanism, leveraging the native attributes of HTML spec. Only one caveat that names are more verbose. |
|
@chengjianhua it may be valid but they bloat your html I was trying to monkey patch SC so that I don't have to do this for every 3rd party component: const StyledLink = styled(({ primary, ...p }) => <Link {...p} />)`
color: ${p => primary ? 'blue': 'white'};
`I came up with something that I think could be a good, non-breaking API: // before first usage of styled
import styled from 'styled-components'
import omit from 'lodash.omit'
styled.transient = propsToOmit => {
return tag => (...args) => {
const Elem = styled(tag)``
return styled(props => <Elem {...omit(props, propsToOmit)} />).call(
styled,
...args
)
}
}
// After monkey patch usage
styled.transient(['primary'])(Link)`
color: ${p => primary ? 'blue': 'white'};
`I rarely monkey patch, and I actually don't need custom props omission very often, but I mainly want it because it makes my code much more readable than the non-monkey patched workaround. It seems to be working quite well for me, and allows me to to gradually change my code. What I like about it:
// blacklist.js
export const global = ['my','list','of','custom','props']
export const buttons = ['primary', 'flat']
// styled-common.js
import { global, buttons } from './blacklist'
import styled from 'styled-components'
const patchedStyled = styled.transient(global)
const buttonStyler = patchedStyle.transient(buttons) // not working in my monkey version but I'm guessing if implemented into sc it can be done
export { patchedStyled as styled }
export { buttonStyler }
// Component.js
import { styled, buttonStyler } from './styled-common'
styled(Link)`` // will not pass down 'my','list','of','custom','props' props
buttonStyler(Button)`` // will not pass down the above props and 'primary' or 'flat' props |
|
@dan-dr I really like your solution. It's worth noting that lodash's omit method is fairly heavy (I measured it at 5.98kB today, Bundlephobia says it's 2.5kB). You might want to try a more lightweight implementation: https://gist.github.com/joemaffei/39976001f70d57b43ade0482994f2db2 |
|
If you don't want to monkey patch Used like this Here's a codesandbox that shows the HOC consuming & discarding the specified props. edit: changed to HoF for compose() compatibility |
|
For a temporary solution we can do it as follows: |
|
Why is this even something Styled Components or any library should be concerned with? This would be much better for React to handle. Pass everything down and have it filtered at the end. React wouldn't even need to have an arbitrary whitelist of valid DOM attributes. As a developer, you would prefix or namespace attributes you want to reach the DOM:
This is extremely easy to lint. Using a dollar prefix as a signal that "this is not a DOM attribute" works well. But it is awkward if it becomes a "this property is implemented as a SC/styletron/etc specific attribute". I'd much rather put a $ sign in front of all props that are not HTML attributes than have it be specific to any library. But at that point, it makes sense to go one step further and only namespace DOM attributes. |
|
@BrandonKai we submitted a RFC to that effect in May of 2017, but it does not look like it will be implemented anytime soon. (react/jsx#81) |
This temporary solution worked for us too. There's a small typo here. Better written as: const SomeComponent = styled(({propIdontWant1, propIdontWant2, ...restProps}) => <ComponentIWantToUseOrHTMLElement {...restProps}/>)`
background-color: ${props => props.propIdontWant1}
`; |
|
Has anyone gotten these workarounds to work in a type safe manner with Typescript? // props is `any`
const MyLabel = styled(({display, ...rest}) => <label {...rest}/>)`
display: ${props => props.display ? 'inline' : 'none'}
`
// Type '{ display: boolean; }' does not satisfy the constraint...
// And: props: never
const MyLabel2 = styled<{ display: boolean }>(({display, ...rest}) => <label {...rest}/>)`
display: ${props => props.display ? 'inline' : 'none'}
` |
|
@tommedema It should be as below. I lost my css intellisense though. Folks coding JS, is it the same for you or it's issue with TS only? |
|
Sadly it's the same in JS. I managed to get my CSS IntelliSense back by assigning the "Transient" component into a variable as below: import React, { LabelHTMLAttributes } from 'react'
import styled from 'styled-components'
const TransientMyLabel2 = ({
display,
...rest
}: LabelHTMLAttributes<HTMLLabelElement> & { display: boolean }) => (
<label {...rest} />
)
const MyLabel2 = styled(TransientMyLabel2)`
display: ${props => (props.display ? 'inline' : 'none')};
` |
|
Adding |
|
couple things I want to add to the conversation: Styletron has already been doing this for a long time and it works well!The approach they use is:
I used styletron in quite extensively and I can say from experience that the approach taken in styletron (to use Maintaining a whitelist causes problemsIt doesn't matter if styled-components maintains that list themselves, or depends on a 3rd party to maintain it.. you're always going to get problems due to "hey add my library's props too"-ism, as well as the ever-evolving HTML attributes spec adding common properties like Current approachWhile styled-components used to maintain a hardcoded regex with all whitelisted properties, as of @probablyup's PR from August 2018 styled-components moved to use "Dan says so"Dan Abramov warns not to use whitelists (styled-components is using a whitelist).
This appeal to authority logical fallacy is brought to you by Dan's good reputation. My use caseRecently I was upgrading an older project that used an older version of styled-components (before the move to
Indeed, this sent me on a wild hunt to figure out why I kept getting this error because I was ignorant to this newly-added experimental HTML attribute. I had assumed (because I had seen In true form, there were many places in the app that used To compound the frustration, Once I figured out what was going on, which took me quite some time because I had to understand how the whitelist worked (there's no mention of whitelist in the styled-components codebase since it's just a dependency now and I wanted to highlight my use case because I think it's a good example of why using a whitelist can lead to:
|
|
@probablyup Any updates on this? Why is this closed? |
|
@vjsingh It was added in 5.1 |
|
@probablyup cool - thanks! |

This commit introduces a new (currently styled-components-specific) concept called "transient props". When a prop is prefixed with a dollar sign (e.g.
$foo={false}), it will only be applied to the immediate component and not forwarded to any deeper children or layers of the component stack.In the case of styled-components, this equates to a styling-only prop that you may consume in your style interpolations but will never end up on the DOM node or in your wrapped component (other props can still be accessed normally). For example:
This would allow us to get rid of the prop-whitelist in the next major version (v5?), which would considerably drop the bundle size of the package.
Fixes #2131
Fixes #2129
Fixes #439