You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I am trying to style a 3rd party "masked" input. The styles are applied correctly, however, there are props I pass into the "styled" element that are used within the CSS logic of the styled component that I don't want passed down to the 3rd party input. This logs an error saying there are undesired props being put on the input (this is also an issue with the 3rd party component that isn't properly stripping out what should go on the input).
I could see it being an enhancement where we specify what props to terminate at the "styled" part. However, this also could just be looked at as the 3rd party component having an issue not removing those props. I'm fine with it being an issue with the 3rd party developer but just wanted to mention the issue and see if this is happening to other people and if it is worth it to build some extra logic in.
Screenshot
Reacted by Siddharth Kshetrapal, Kristofer Giltvedt Selbekk, Alex Rapley, Mike Staub, Deividas Karžinauskas, Gabriel Bieules, Matt Duffin, Shu Uesugi, Jason Axelson, Olivier Tassinari and 213 more
Reacted by Varun Singh, Steve Meredith and Michał Lach
Right now, styled-components is a "smart wrapper", in that it uses an attribute whitelist to only route actual HTML attributes through to DOM nodes. This whitelist is suboptimal because if every React lib has one we'd end up with huge bundles due to whitelist duplication.
What we would want is a nice API for separate attributes and styling props. API ideas very welcome here! 😊 (#365 might be a step in the right direction)
Reacted by Jesse Sutherland, Puranjay Jain, Zhenxi Mi, Matt Duffin, Benjamin Borowski, Tim Brandin, Ganesh Godshelwar, Joe, William Cantin, Andrew Smiley and 13 more
Reacted by Jason, Shripad Krishna, Matthew Creager, Gurwinder Singh, Mike Staub, Puranjay Jain, Kristofer Giltvedt Selbekk, Zhenxi Mi, Tim Brandin, Benjamin Borowski and 3 more
I haven't dug into the source code to see if props is passed into the css template as a copy or a reference. But I think this could be solved by sending a copied version of the props object that has a pop method similar to a python dictionary. For example
constButton=styled.Button` width: ${(props)=>props.width ? props.pop('width') : '100%'}; &:active { /* width is still available as it isn't removed until after each dynamic property is updated. Only one call to pop is needed although there is no harm in calling it again */ width: ${(props)=>props.width ? `calc(${props.width} + 50%)` : '150%';}`
The width string is stored in a list of keys and after all dynamic properties have been applied a new props object without the keys is passed to the component.
Reacted by Nicola Bertelloni, Hein Haraldson Berg, Harrisson Restrepo, Kolomiiets and Taras
I'm having this issue currently. I don't completely understand @gabewillen 's suggested solution. Is the list of keys something that is going to be added to the styled-components source code, or something a library user would create to remove the intended prop?
@bsbechtel The list of keys is not added to the actual Component. Its encapsulated inside the string template function and populated after the first interpolation of the template string. That being said I actually prefer #532 as its easier to see what props are strictly for style and shouldn't be passed as a property to the component.
Apply transformations to all props that are style props and are type checked by react-native (e.g. margin, padding etc.) before passing them to the underlying component. Implementing this would involve figuring out an exhaustive list of such props that are typechecked and maintaining it as new props are added upstream.
Others
Just a mention for completeness,
Ditch the StyleSheet or inline style and pass transformed layout props down as direct inline props to the underlying component overriding the props passed to the styled component. This assumes that this weird bahavior is consistent for all layout props.
Reacted by Jed Watson, Kristofer Giltvedt Selbekk, Nathaniel Thomas, Anton Puko, Robert Valmassoi, Vlad Nicula, qlin, Zhenxi Mi, Rubens Mariuzzo, Juan Carlos Sanchez Cardenas and 53 more
Reacted by Alexander and Abdelkoddous
Reacted by Pavel
Reacted by Zhenxi Mi, Rubens Mariuzzo, Miro Yovchev, Parmesh Krishen, Nate Ryall, Daniel K., William Cantin, Jeffrey Powers, Pavel, damianon and 1 more
Both of these mean no static prop-type validation, which is certainly a nice-to-have. It (likely) won't extend to Vue. But it does mean you don't have to explicitly declare styling props.
I'd really like to find a good solution to this, but I think we might need to break something about the original design to do it.
Firstly, a question: how important is proptype validation to you? And do you think an include or exclude list is preferable.
There's a problem with anything automatic like @gabewillen's suggestion:
constButton=styled.Button` width: ${props=>props.width ? (props.pop('width')-props.pop('padding'))+'px' : '100%'};`<Buttonwidth={500} padding={16}/>// both popped<Buttonpadding={16}/>// padding still passed through
Where prop-passing is a side-effect, these edge-cases will appear. Given that we now have attrs, I'm starting to tend towards something like this:
constA=styled(Link).attrs({_include: 'href target'})` font-size: ${props=>props.large&&'1.2em'}; color: ${props=>props.red ? 'red' : 'black'};`<Ahref="#"largered/>// only 'href' passed through.constB=styled(Link).attrs({_exclude: 'large small red blue'})` ... same as A ...`<Bhref="#"largered/>// only 'href' passed through.
With A, we could predefine whitelists for each HTML element, eg:
// from https://developer.mozilla.org/en-US/docs/Web/HTML/AttributesconstGLOBAL_ATTRS='accesskey contenteditable contextmenu ... style tabindex title'styled.div=styled('div').attrs({_include: `${GLOBAL_ATTRS}`})styled.a=styled('div').attrs({_include: `${GLOBAL_ATTRS} href target media hreflang ping rel shape`})// etc
But that doesn't help with something like React router's Link, or any other component where there might be a lot of attributes you want to pass through.
I'm somewhat more inclined to go with an exclusion approach. After all, any property you pass to a Styled Component is either part of its API or an argument for its children. So, in order to stop a prop being passed on, perhaps you have to add it to something like PropTypes, therefore explicitly making it part of the outer API.
I feel like something similar to propTypes is the right approach here but still just feeling my way towards a syntax I like. Happy for feedback though!
Reacted by diondiondion, Aaron McAdam, Patrick Krawczykowski, Christoforos Varakliotis, Deividas Karžinauskas, Fred, Mark Penner, Sam Hogan, Rafael Mello Campanari, rafaelcseventh and 1 more
@lcswillems that won't work the way you write it, because the first argument to div will just be '\nwidth: [Function function]px;\nheight: ...'. And if you use the template string form, there's no place to put the second argument…
Based on what @gaearon proposing imo it would be better to change the API to this....
const Button = styled.div`
color: #333;
padding: 0.5rem;
`.variants({
disabled: css`
color: #E6E6E6;
opacity: 0.6;
`,
primary: css`
color: blue;
border-radius: 50%;
`
});
// usage:
<Button type="submit" style={{ primary: true, disabled: false }} />
// For people targeting modifiers in other components you can do....
Button.primary // .sc-b4839243
Button.disabled // .sc-b34234z
Reasons why:
This allows you to easily discern what each modifier applies.
No need for HTML prop white list because all modifiers from come "style"
Static typing friendly no longer any need for styled.div<{disabled: boolean}> because it can be typed as StyledComponent<P & ReturnType<variants> (pseudo code types)
No longer a need for multiple checks on the same condition IE the modifier "disabled" in styled-components v4 can lead to multiple functions all checking for "disabled" equality and applying a different property.
Can use css targetting to target different modifiers as the output can only be 3 class names I.E other people consuming Button can target when its primary by... css${Button.primary} {color: grey}
People can no longer use "stateful" css I.E take a physical run time value and set that property in the style sheet, this is a good thing because that leads to many css className outputs when you can already do stateful css with inline styles. Stateful CSS through styled-components in my eyes in an anti-pattern.
Makes JSX more readable as styles are logically separated from HTML prop names.
Familiar BEM-like syntax.
Reacted by Yordis Prieto, Steve Meredith and Artem Sapegin
I have seen multiple viable solutions proposed in this thread. I doubt every single person is going to be satisfied with what ever solution is chosen, is it time somebody made an executive decision? We have been waiting 3 years for this to be resolved. 🤷♂
Reacted by garyee, Gökhan, Dariusz Rzepka, Cole Peters, Zack Sunderland, Anthony Fields, Julien Fouilhé, Varun Singh, Francesca Mischi, Joseph Cho and 5 more
I think the executive decision has already been made — "do nothing".
Thus people are exploring third party solutions that leap-frog this issue entirely. For example, styled-system is a common library that exacerbates this problem. The next generation is theme-ui which puts all style props in a single sx prop. I'm still using styled-system instead of theme-ui, but I'm using the sx prop approach.
Example:
importstyledfrom"styled-components"importcss,{SystemStyleObject}from"@styled-system/css"interfaceStyleProps{sx?: SystemStyleObject}exportconstBox=styled.div<StyleProps>(props=>css(props.sx))exportconstText=styled.p<StyleProps>(props=>css({// Set some default stylesfontSize: 1,mt: 0,mb: 3,lineHeight: 1.5,
...props.sx,}))
Reacted by Evgeny Timoshenko, Steve Meredith, Son Dang, Miron, Cyrus Venn Casada, RyanDagg, Alex Lobera, Anthony Fields, Wallace Sidhrée, theanhmx and 2 more
This would be great to at least have a statement from the team to know if they plan to solve it in the core or if we should just do it by ourselves.
Reacted by garyee, Taylon, Anthony Fields, Steve Meredith, Son Dang, Varun Singh, Alex Gabites, Wallace Sidhrée, Kirill Alexander Khalitov, Artem Zakharchenko and 5 more
Reacted by Varun Singh, Steve Meredith, Wallace Sidhrée, Artem Zakharchenko, Tom and Andrey Ivanov
Super frustrating that this issue still hasn't been solved despite having heaps of good discussion and ideas added to address it since I started using styled-components ~3 years ago.
This has to be one of my only problems when using styled-components and its just reaching a point where I'm beginning to consider migrating projects to emotion simply because they solved (or at least tried to solve) this issue ages ago.
I really do appreciate the hard work that lots of people have put into this library, but the least the maintainers could do is provide a solid answer on this topic.
Reacted by Gökhan, Pierre de la Martinière, Kirill Alexander Khalitov, Alasdair McLeay, Karl Horky, Dariusz Rzepka, Doug Richar, Anthony Fields, Mikkel Wied Frederiksen, garyee and 16 more
Activity
[-]Terminate props before passing to 3rd party[/-][+]Separate HTML attributes from styling props[/+]mxstbr commentedon Jan 31, 2017
You hit upon a very interesting point there that @gaearon has been talking about and we've been thinking about.
Right now,
styled-componentsis a "smart wrapper", in that it uses an attribute whitelist to only route actual HTML attributes through to DOM nodes. This whitelist is suboptimal because if every React lib has one we'd end up with huge bundles due to whitelist duplication.What we would want is a nice API for separate attributes and styling props. API ideas very welcome here! 😊 (#365 might be a step in the right direction)
leonwilly commentedon Feb 22, 2017
I haven't dug into the source code to see if props is passed into the css template as a copy or a reference. But I think this could be solved by sending a copied version of the props object that has a pop method similar to a python dictionary. For example
The width string is stored in a list of keys and after all dynamic properties have been applied a new props object without the keys is passed to the component.
jacobp100 commentedon Feb 23, 2017
See also: #403 #527. Should we close those bugs in favour of this?
jacobp100 commentedon Mar 1, 2017
I meant close the others and keep this one open 😜
bsbechtel commentedon Mar 1, 2017
I'm having this issue currently. I don't completely understand @gabewillen 's suggested solution. Is the list of keys something that is going to be added to the styled-components source code, or something a library user would create to remove the intended prop?
leonwilly commentedon Mar 2, 2017
@bsbechtel The list of keys is not added to the actual Component. Its encapsulated inside the string template function and populated after the first interpolation of the template string. That being said I actually prefer #532 as its easier to see what props are strictly for style and shouldn't be passed as a property to the component.
jacobp100 commentedon Mar 3, 2017
Just to tie together comments in other threads, here are some ideas that were thrown around,
Explicitly Define Props
Apply css-to-react-native to Style Props
Others
Just a mention for completeness,
This won't actually work in RN.
jacobp100 commentedon Mar 4, 2017
Interestingly, I just saw vue-styled-components, which seems to require knowing prop types upfront. They did it in the constructor.
I think this is my favourite so far!
bsbechtel commentedon Mar 6, 2017
+1 for the vue-styled-components solution
jacobp100 commentedon Mar 6, 2017
One more idea, which may be terrible, is to either pass in all styled props as a single prop,
Or require a prefix or suffix for styled props,
Both of these mean no static prop-type validation, which is certainly a nice-to-have. It (likely) won't extend to Vue. But it does mean you don't have to explicitly declare styling props.
Just adding it so we consider all options!
geelen commentedon Mar 7, 2017
I'd really like to find a good solution to this, but I think we might need to break something about the original design to do it.
Firstly, a question: how important is proptype validation to you? And do you think an include or exclude list is preferable.
There's a problem with anything automatic like @gabewillen's suggestion:
Where prop-passing is a side-effect, these edge-cases will appear. Given that we now have
attrs, I'm starting to tend towards something like this:With
A, we could predefine whitelists for each HTML element, eg:But that doesn't help with something like React router's
Link, or any other component where there might be a lot of attributes you want to pass through.I'm somewhat more inclined to go with an exclusion approach. After all, any property you pass to a Styled Component is either part of its API or an argument for its children. So, in order to stop a prop being passed on, perhaps you have to add it to something like
PropTypes, therefore explicitly making it part of the outer API.Of these,
xis definitely being passed down to the div, butyandzare maybe not. Maybe they have defaults, maybe they have types? What about:Or something to that effect. Alternatively:
I feel like something similar to
propTypesis the right approach here but still just feeling my way towards a syntax I like. Happy for feedback though!191 remaining items
topaxi commentedon Nov 11, 2019
@hrasoa no, as soon as I provide an
asprop, the component with the filtered props is no longer executed.hrasoa commentedon Nov 11, 2019
@topaxi yes this don't work with the "as" prop, you have to do the same in the switched component:
lcswillems commentedon Nov 15, 2019
I have just written an RFC for filtering forwarded props: #2878
Would you like a solution like this?
TL;DR It consists of adding a second parameter for filtering props. The current solution:
is turned into:
This is easy to write and to understand, and props filtering (which is not the important part of the definition) is sent at the end of the definition.
wmertens commentedon Nov 15, 2019
@lcswillems that won't work the way you write it, because the first argument to div will just be
'\nwidth: [Function function]px;\nheight: ...'. And if you use the template string form, there's no place to put the second argument…lcswillems commentedon Nov 16, 2019
That's true! So in this case, only:
would work.
ShanonJackson commentedon Dec 29, 2019
Based on what @gaearon proposing imo it would be better to change the API to this....
Reasons why:
styled.div<{disabled: boolean}>because it can be typed asStyledComponent<P & ReturnType<variants>(pseudo code types)${Button.primary} {color: grey}Steveeeie commentedon Jan 3, 2020
I have seen multiple viable solutions proposed in this thread. I doubt every single person is going to be satisfied with what ever solution is chosen, is it time somebody made an executive decision? We have been waiting 3 years for this to be resolved. 🤷♂
flybayer commentedon Jan 3, 2020
I think the executive decision has already been made — "do nothing".
Thus people are exploring third party solutions that leap-frog this issue entirely. For example,
styled-systemis a common library that exacerbates this problem. The next generation istheme-uiwhich puts all style props in a singlesxprop. I'm still usingstyled-systeminstead oftheme-ui, but I'm using thesxprop approach.Example:
martpie commentedon Jan 14, 2020
This would be great to at least have a statement from the team to know if they plan to solve it in the core or if we should just do it by ourselves.
South-Paw commentedon Jan 26, 2020
Super frustrating that this issue still hasn't been solved despite having heaps of good discussion and ideas added to address it since I started using styled-components ~3 years ago.
This has to be one of my only problems when using styled-components and its just reaching a point where I'm beginning to consider migrating projects to emotion simply because they solved (or at least tried to solve) this issue ages ago.
I really do appreciate the hard work that lots of people have put into this library, but the least the maintainers could do is provide a solid answer on this topic.
wasinsandiego commentedon Jan 28, 2020
Totally agree with @South-Paw on this. Never ran into this issue with
emotion, but at least they have a way to handle the odd cases they don't handle it for you.https://emotion.sh/docs/styled#customizing-prop-forwarding
penx commentedon Feb 7, 2020
As far as I'm aware, #2392 implements shouldForwardProp in the same way as emotion and would resolve this issue.
There was agreement in #2780 (comment) to implement something like shouldForwardProp.
I would propose following emotion's implementation and name to improve compatibility for those moving from one library to another.
Can #2392 be reopened?
diondiondion commentedon Feb 7, 2020
Nice to see some movement on this. :) I'm not a fan of the emotion API with all the front-loaded config*, but hey-ho, if it gets the job done.
*
.attrs({...})is bad already, adding.withConfig({...})into the mix will make styled-component definitions pretty ugly to look at.karlhorky commentedon Feb 9, 2020
Thanks @stevesims for reopening the
shouldForwardPropproposal in #3006 👍 Go upvote there!