Repository navigation
Description
First off, thanks again for your hard work on sc4! I'm really enjoying the new features it introduced, the as prop in particular. I got really excited when I read about it first, as we had just introduced a Base component to our UI library that would enable the same functionality for all components that used it. We even chose the same prop name.
But as we know the devil's in the details, and so I noticed during migration to v4 that there's an important difference between letting a Base component handle the as prop and using s-c's own prop: The first styled component to receive the as prop uses it directly, and there's no way other than using a different prop name to prevent this. This is not a problem when all components wrapped with styled() are styled components themselves, but when they're not (and quite a few of our UI elements aren't), it leads to veeeery unexpected behaviour.
It's basically the same issue that the ReaKit people are facing: ariakit/ariakit#226
Now, our codebase is already using the as prop and we'd strongly prefer not to change it. Not just because it'd be a huge amount of work. It would also be a shame since there should be a consistent API for changing the rendered element/component of both "plain" sc components and our own custom ones. I WANT to use s-c's as prop. But due to the issue mentioned above, achieving this is very complicated at the moment.
Consider this innocent piece of code for example:
const CustomNavBarTab = styled(NavBarTab)`
/* ... styles ... */
`;
render(
<CustomNavBarTab as="a" ref={this.refHandler} ... >
);where NavBarTab is NOT a primitive styled-component. It does take the as prop (and ref) and forwards it to a nested styled-component. This used to work with the Base component, but breaks with sc's 'as' prop, since as="a" effectively changes the above component definition to const CustomNavBarTab = styled('a'), disregarding all of NavBarTab's styles & behaviour.
To work around this fully while trying to keep the outer component API the same, something crazy like the below would have to be written:
const StyledCustomNavBarTab = styled(React.forwardRef(({innerAs, ...props}, ref) =>
<NavBarTab {...props} as={innerAs} ref={ref} />
))`
/* ... styles ... */
`;
const CustomNavBarTab = React.forwardRef(({as, ...otherProps}, ref) => {
return (
<StyledCustomNavBarTab
ref={ref}
innerAs={as}
{...otherProps}
/>
);
});You'll probably agree that this really shouldn't be necessary just to keep refs and the "as" prop working in a consistent way.
As you know from my persistent lobbying for an sc-specific API for filtering props near the component definition, the goal of all of this is to keep styled-components a "transparent" layer. I don't want to require component users to know whether a component is a primitive styled-component or not.
I WISH I could just write the component somewhat like this, indicating to styled-components that the as prop should be passed down to the wrapped component:
const CustomLinkTab = styled(NavBarTab, {ignoreAs: true})`
/* ... styles ... */
`;I don't care much about the specifics of the API as long as it doesn't require piling on wrapper components just for passing on or tranforming or filtering props.
Is this something you'd consider adding to styled-components? I imagine it would be fairly easy to implement, but the hard part would be settling on an API for it.
Activity
pepf commentedon Oct 22, 2018
Agree with the above. I can imagine this is quite a pain if you already implemented the "as"-prop yourself.
I think I stumbled on this from a more "greenfield" perspective. I was hoping to use the "as" prop out-of-the-box in v4 but when actually using it for a simple "buttons as links" example I quickly ran into the issue.
I can obviously write my own implementation as well (with the aforementioned complexities in mind), but shouldn't this (pretty basic) example be covered ?
Example:
https://codesandbox.io/s/0x0rkr2mrp
dlebedynskyi commentedon Nov 2, 2018
We are seeing same problem with our adoption of 'as'.
Attempt we had was to use BaseComponent that will handle 'as' and use next level components to add
styled. Expectation was thataswill be actually used on bottom base component.Here is example of code that does not work:
What works actually are these 2 cases
or this
We were really excited about using native styled-components
asproperty. but it looks like what we are trying to build is closer to 'is' from styled-system.I'm wondering is we can actually enable passing "as" to bottom component and actually allow to compose styles using it.
satya164 commentedon Nov 7, 2018
Something like this should work:
If you have a lot of these, you could also create a helper:
diondiondion commentedon Nov 8, 2018
@satya164 That's the workaround I mentioned in the opening post, but it's just a workaround and pretty clunky at that. The point of this feature request is to achieve transparency between low-level, re-usable styled-components and those that were created e.g. for a specific one-off context. Having to go back and forth between
innerAs(and/orinnerRef) creates a lot of extra complexity, API inconsistency, and required knowledge by the component users.quantizor commentedon Nov 9, 2018
"innerAs" suffers from the same issue as the transient props proposal, which is it only works for 2 component layers. If there is a third one in the stack that also uses "as", it all breaks down. I wish there was a way to force along the JSX namespaces proposal, because that would take care of this whole issue.
diondiondion commentedon Nov 9, 2018
@probablyup How do you see JSX namespaces solving this issue, i.e. how would we as component creators determine which component layer the "as" prop should apply to if there were namespaces? To me it seems like prop remapping would still be necessary, which means intermediate components & extra ref forwarding layers, too.
I'd be super interested to get some kind of insight into the philosophy you're following with styled-components & the reasoning for favouring prop-handling solutions at component-usage time (JSX) rather than near the component-definition (i.e.
styled(Comp).options). Would Spectrum be the right place to ask about this?quantizor commentedon Nov 9, 2018
diondiondion commentedon Nov 13, 2018
So your proposed solution is to just use different props for primitive styled-components (
sc:asor whatever it'll be) versus "normal" react components (as).If so, it's a solution for this specific scenario but not a proper solution to the core problem. There NEEDS to be a reasonably simple way to make the props API of a styled-component transparent & identical to any other react component.
I can't imagine anyone building a UI component library wanting to require their users to know about whether a component is a primitive styled-component or not in order to use it correctly.
Is this scenario not a concern for you?
quantizor commentedon Nov 13, 2018
mxstbr commentedon Nov 13, 2018
For me personally, what makes styled-components nice to work with is that it's "just React components". I specifically don't have to think about whether the component I'm targeting or not is a styled-component or not, I just use its public API and that's that.
quantizor commentedon Nov 13, 2018
You still have to know what props you're receiving in the styled component if you're adapting based on props. So, at the end of the day, you do still need to know it's a styled component.
quantizor commentedon Nov 13, 2018
Not having to know what you're consuming is a nice dream, but doesn't work in reality for anything other than totally static components.
diondiondion commentedon Nov 13, 2018
I disagree. As a UI library creator (and to be honest, everyone building custom UI components for a reasonably large react project is one) it's my job to create a consistent API across components. Expecting different props depending on an implementation detail is simply not acceptable. What if the component is changed from a s-c primitive to a normal React component, or the other way around? Expect users to change the props across their apps? No way.
In short, your proposed solution won't allow me to do this, so the only workaround will be to wrap every primitive styled component in an otherwise useless wrapper component (& a forwardRef wrapper for full transparency).
Changing the underlying element of a component is not advanced usage, it's an essential bread-and-butter task for writing accessible & correct HTML.
diondiondion commentedon Nov 13, 2018
Why would you need to know that? Of course you need to know about the props API in general. But there's a HUGE difference between knowing how to change, let's say, the font size of a component via a dedicated prop, and knowing whether to use
asorsc:asdepending on an entirely arbitrary factor like whether the component is a styled-component primitive or a "normal" react component.mxstbr commentedon Nov 13, 2018
Yeah, in the styled component of course I need to know it's a styled component, but from the outside I really don't need to care right now. There's 0 need for me to be aware if a component is styled or not, it's just a component that gets passed a certain set of props, and I can swap styled-components out as an implementation detail whenever I want. Namespaces would destroy that, which I personally (again, my personal thinking after using s-c for a bit) really like, the library staying an implementation detail.
quantizor commentedon Nov 13, 2018
Again, your solution only works for one component layer. The namespacing proposal works for any number of component layers, assuming they chose unique namespaces (this seems reasonable.)
One of the big things that's been thrown around a lot on this issue are wrapped components that also support "as", potentially going down multiple levels. Your proposal only addresses the topmost layer and doesn't make composition any easier. That's the central issue. it also requires having to put in all sorts of config for any prop we add in the future, which is a nonstarter.
mxstbr commentedon Nov 13, 2018
Yeah @probablyup is right about that—this specific API only solves the issue one layer deep, which isn't ideal. Is there another way to handle this apart from forking JSX and adding namespaces?
diondiondion commentedon Nov 13, 2018
On the contrary, this seems like madness to me. There's a reason the core React team has implemented the
forwardRefAPI to allow making refs transparent...Maybe I don't understand enough about how styled-components work internally, but the initial problem described in this issue is that the
asprop is being applied prematurely. If I could tell sc to ignore the prop and pass it down instead, the problem would be solved at that level. What the "lower" layer does with theasprop isn't of the top component's concern anymore, it's been passed on. Can you post an example of a multi-layer component where this wouldn't work?I realise this is part of a bigger topic (namely, #439). It can be solved in a future-proof way. (How many custom props to you expect to have to add in the future, anyway)?
These are the two big issues here:
My proposal would be two new methods, one for specifying a per-component blacklist for dropping props, and one for specifying a per-component whitelist for intentionally passing on props that would otherwise be consumed by sc (like
as). This would give us all the power we need and is as future-proof as it can get, I think.Is it the end-all solution to dropping the props whitelist? Maybe not. But it would give us the tools we need to solve very real existing problems right now.
As I said more than a year ago in my comment in issue 439, this is not a problem exclusive to styled-components. Component props have to be managed at some point. We just need the tools to do so.
diondiondion commentedon Nov 13, 2018
The link to my comment in #439 doesn't work due to github's pagination, here's what I said back then:
View Comment:
I quite liked the idea of namespaced props in the beginning, but the more I think about them, the more I start to dislike them as a solution to this specific issue.
There's 3 main reasons for it:
Filtering unused props is not a problem exclusive to styled-components by far, and namespaces don't allow solving it in the way it's most commonly solved. Instead, they just shift the problem:
Namespaces for filtering put ease of component creation (one-time task) over ease of component use (recurring task)
Namespaces affect component APIs depending on how they were created (which you should not have to know about)
Let me elaborate on each point:
1. It's not a problem exclusive to styled-components
I generally pass remaining props down to either the main element of presentational components, or to their topmost JSX element. I consider this best practice as it helps making components composable and extensible.
Since I'm the creator of the component & I know which custom props it will use, I can easily make sure those won't be passed down -- I do this either by destructuring (when I'm going to use the prop in render), or by
deleteing it from the rest (when I'm not).Here's an almost-real-world example showing both methods:
Sure, this doesn't look elegant, but it surely beats making the component API more complex than it needs to be just to handle prop splitting. There's a good reason you probably won't find a react component in the wild that isn't making use of first-level props just to avoid this. After all...
2. Ease of component use is more important than ease of component creation
Splitting props into those passed down and those that the component consumes is easy while you're creating the component and every detail about it is fresh in your mind. But when you just want to use the component, the difference can be less than obvious, and you might end up accidentally putting props under the namespace that shouldn't be under it, or forget to add them to the namespace. I don't want the users of my component to have to worry about what's essentially an implementation detail.
Filtering props inside of a component is work done once. Giving props the correct namespace on a component instance is work done every single time the component is used.
3. Namespaces make component APIs dependent on how they were created
I use styled-components for all presentational components, but not all my presentational components are "plain" styled-components. Even something as seemingly simple as a
Buttoncomponent can be composed of multiple styled components, but I wouldn't want this fact to affect the component's API.As it doesn't make sense for only half of my component library to have namespaced presentational props, I'd have two options:
(And of course, not all presentational props are for use within styled-components, for example boolean props that just toggle whether to show an element or not. It seems absurd to give them a namespace for consistency.)
So, with all that said, here's
What I propose instead
Instead of trying to hide the fact that the whitelist is gone by splitting props at JSX level, embrace & promote the idea that prop filtering is part of the component author's responsibility.
In other words: Pass down all props by default & focus on providing a good API for blacklisting props from being passed down.
This is what all the HOC-based workarounds that exist now are doing, and it's what I think this library should aim to make both easy and explicit.
Couldn't it be as simple as the following example? Would it be so bad having to explicitly state which props you don't want passed down?
dlebedynskyi commentedon Nov 13, 2018
to follow up conversion regarding 'as'.
we ended up having following tag component as base
Tag Component
This component later is being used in following way
this allowed us to use something along this lines
What is not convenient is need to have both 'blacklist' and 'defaultBlacklist' - one for project exposure, 2nd for internal component library. We could not use one, since logic of contact/replace was becoming tricky.
Ideally 'as' would work similar to above
tag.*by default for us is cleaning both defaultBlacklist and blacklist.diondiondion commentedon Jan 22, 2019
The astroturf library solves this issue by allowing to specify an
allowAsoption like this:Looks clean and does the job.
kizu commentedon Mar 25, 2019
Wanted to chime in: this is an issue that I have with styled-components as well. Basically, I want to create a component that should have a certain HTML structure, and its root element should be configurable via a prop, and
asseems to be the perfect fit.But then it would be impossible to style it with styled-components without losing this feature.
The perfect solution, in my opinion, would be if styled-components would look at the wrapped component's propTypes, and if it would see that this component handles the
asprop itself, styled-components would just passasto this component.What all of you think of a solution like this?
Alternatively, in most cases it would be safe for styled-components to use
asprop only if it was initialised with an HTML tag for a component, and for any custom components it could assume that that component could handle theasprop by itself.In my practice you never want to redefine the component via
aswhen used withstyled(MyComponent), but in most cases you want to do so withstyled.divetc.stonebk commentedon Aug 28, 2019
@diondiondion what do you think of this proof of concept API: #2448 (comment)
diondiondion commentedon Aug 28, 2019
@stonebk I wouldn't be too fond of it as an official API.
forwardRefis already a bandaid solution that would be more elegantly solved as a seamless part of react's API (i.e. all functional components would receive a ref as the second parameter), so I wouldn't model other APIs after it.I don't want to do the forwarding manually, I just want to tell s-c to ignore
asand pass it on like the other props, and without messing up the built-inrefforwarding.Something like the astroturf API linked to above would be perfect IMO.
stonebk commentedon Aug 28, 2019
I saw you mention the astroturf API early, but I don't think it clicked while I was looking at it yesterday. You're right, I think an "ignore as" option would really give us full flexibility.
abutterworth commentedon Apr 16, 2021
This is a stale thread, but here's my solution to this problem for anyone one else passing by:
The problem
Most components in my library implement an
asprop (like React-Bootstrap) and this prop is already in use throughout a large codebase. We would like to adopt styled-components by wrapping our existing components – but now whereverasis currently used in the code base we get (mildly) unexpected behavior. How do we adopt styled-components without asking everyone to update their usages ofastoforwardedAs.A solution
A
forwardAsPropHOC:Usage in a
Buttoncomponent in the component library:The end result is no disruptive change for consumer of the component library.
kitten commentedon Aug 9, 2021
There's several workarounds to this, so given a lack of activity and
attrssupporting "as", I'll go ahead and close this.fix(Stack): allow polymorphic behaviour for extended components