Skip to content

Feature Request: Option to pass "as" prop down to wrapped component when using styled(Comp) #2129

Closed

Description

@diondiondion

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

  1. pepf commented on Oct 22, 2018

    @pepf

    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

  2. dlebedynskyi commented on Nov 2, 2018

    @dlebedynskyi

    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 that as will be actually used on bottom base component.

    Here is example of code that does not work:

       <LabelText as="span" bold>
          Status:&nbsp;
        </LabelText>
        <StatusText as={tag.span} id="dashboard-card-status" bold topStatus={topStatus}>
          {topStatus}
        </StatusText>
    

    What works actually are these 2 cases

    const Magictext = React.forwardRef((props, ref) => (
      <Text {...props} as={tag.span} ref={ref} />
    ));
    
    const StatusText = styled(Magictext)`
      ${({ theme, topStatus }) => {
     // rest of styling
    }
    
    export const StatusWrapper = ({ topStatus }: Props) => (
      <Wrapper middle>
        <StatusText id="dashboard-card-status" bold topStatus={topStatus}>
          {topStatus}
        </StatusText>
      </Wrapper>
    );
    

    or this

    const LabelText = styled(Text)`
      color: ${({ theme }) => theme.colors.grayscale.base};
    `;
    
    export const StatusWrapper = ({ topStatus }: Props) => (
      <Wrapper middle>
        <Text as={LabelText} bold>
          Status:&nbsp;
        </Text>
     </Wraper>
    );
    

    We were really excited about using native styled-components as property. 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.

  3. satya164 commented on Nov 7, 2018

    @satya164

    Something like this should work:

    const CustomLinkTab = styled(({ innerAs, ...rest }) => <NavBarTab as={innerAs} {...rest} />)`
      ...
    `;
    
    <CustomLinkTab innerAs="a" />

    If you have a lot of these, you could also create a helper:

    const handleAs = Comp => ({ innerAs, ...rest }) => <Comp as={innerAs} {...rest} />;
    
    const CustomLinkTab = styled(handleAs(NavBarTab))`
      ...
    `;
  4. diondiondion commented on Nov 8, 2018

    @diondiondion
    Author

    @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/or innerRef) creates a lot of extra complexity, API inconsistency, and required knowledge by the component users.

  5. quantizor commented on Nov 9, 2018

    @quantizor
    Contributor

    "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.

  6. diondiondion commented on Nov 9, 2018

    @diondiondion
    Author

    @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?

  7. quantizor commented on Nov 9, 2018

    @quantizor
    Contributor
  8. diondiondion commented on Nov 13, 2018

    @diondiondion
    Author

    sc:as= semantic:as= etc

    So your proposed solution is to just use different props for primitive styled-components (sc:as or 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?

  9. quantizor commented on Nov 13, 2018

    @quantizor
    Contributor
  10. mxstbr commented on Nov 13, 2018

    @mxstbr
    Member

    Sorry but the consumer has to know what types of components they’re working with.

    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.

  11. quantizor commented on Nov 13, 2018

    @quantizor
    Contributor

    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.

  12. quantizor commented on Nov 13, 2018

    @quantizor
    Contributor

    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.

  13. diondiondion commented on Nov 13, 2018

    @diondiondion
    Author

    Sorry but the consumer has to know what types of components they’re working with. After thinking a lot about it, if you’re intending to modify the styling via props or something advanced like an “as” override, it’s not unreasonable to expect that.

    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.

  14. diondiondion commented on Nov 13, 2018

    @diondiondion
    Author

    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.

    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 as or sc:as depending on an entirely arbitrary factor like whether the component is a styled-component primitive or a "normal" react component.

  15. mxstbr commented on Nov 13, 2018

    @mxstbr
    Member

    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.

    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.

  16. quantizor commented on Nov 13, 2018

    @quantizor
    Contributor

    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.)

    knowing whether to use as or sc:as depending on an entirely arbitrary factor

    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.

  17. mxstbr commented on Nov 13, 2018

    @mxstbr
    Member

    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?

  18. diondiondion commented on Nov 13, 2018

    @diondiondion
    Author

    The namespacing proposal works for any number of component layers, assuming they chose unique namespaces (this seems reasonable.)

    On the contrary, this seems like madness to me. There's a reason the core React team has implemented the forwardRef API to allow making refs transparent...

    Again, your solution only works for one component layer.

    Maybe I don't understand enough about how styled-components work internally, but the initial problem described in this issue is that the as prop 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 the as prop 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?

    it also requires having to put in all sorts of config for any prop we add in the future, which is a nonstarter.

    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.

  19. diondiondion commented on Nov 13, 2018

    @diondiondion
    Author

    The link to my comment in #439 doesn't work due to github's pagination, here's what I said back then:

    View Comment:

    We’re waiting for a JSX solution to this problem, namely namespaces for props. Until then most people seem to resort to HOCs (yes, you don’t need to say that you do as well anymore 😉)
    We’ve put forward alternative APIs but they’re all not elegant enough in our opinion

    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:

    1. 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:

    2. Namespaces for filtering put ease of component creation (one-time task) over ease of component use (recurring task)

    3. 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:

    render() {
    	const {text, ...otherProps} = this.props;
    
    	delete otherProps.submitOnEnter;
    
    	return (
    		<textarea
    			{...otherProps}
    			value={text}
    			onKeyDown={this.onKeyDown}
    		/>
    	);
    }
    

    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 Button component 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:

    1. Wrap all plain styled components in a functional component that maps namespace-less props to the namespace. Now the simplicity of using plain styled-components is gone.
    
    2. Add the namespace to _all_ presentational props of complex/multi-element presentational components even if they won't be passed directly to styled components. Enter prop-passing hell.
    

    (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?

    const Button = styled.a`
    	background: transparent;
    	color: white;
    
    	${props =props.primary && css`
    		...
    	`}
    
    	${props =props.size && css`
    		...
    	`}
    `
    Button.deleteProps = ['primary', 'size']
    
  20. dlebedynskyi commented on Nov 13, 2018

    @dlebedynskyi

    to follow up conversion regarding 'as'.
    we ended up having following tag component as base

    Tag Component
    
    const styledSystemDefaultBlacklist = [...Object.keys(allPropTypes), 'theme'];
    
    const omit = (obj, keys) =>
      Object.keys(obj).reduce(
        (agg, key) => (keys.indexOf(key) > -1 ? agg : { ...agg, [key]: obj[key] }),
        {}
      );
    
    export const Tag = React.forwardRef(
      ({ is = 'div', blacklist = [], defaultBlacklist = [], ...props }, ref) =>
        is
          ? React.createElement(is, {
              ref,
              ...omit(
                props,
                styledSystemDefaultBlacklist.concat(defaultBlacklist, blacklist)
              ),
            })
          : is
    );
    
    Tag.displayName = 'Clean.div';
    
    Tag.defaultProps = {
      blacklist: [],
      defaultBlacklist: styledSystemDefaultBlacklist,
    };
    
    tags.forEach(tag => {
      Tag[tag] = props => React.createElement(Tag, { is: tag, ...props });
      Tag[tag].displayName = `Clean.${tag}`;
    });
    
    export default Tag;
    
    

    This component later is being used in following way

    const Text = styled(tag.p)`
     // some styles
    ` ;
    
    const Text = React.forwardRef((props, ref) => {
    // component logic
    return <StyledText {...props} ref={ref} />;
    };
    

    this allowed us to use something along this lines

    <Text is={tag.div} mr={1} > as div </Text>
    <Text is={ProjectStyledText} spacing="none" m={1} customProperty="123" blacklist=["customProperty"]> as custom element with props respected </Text>
    
    

    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

    • allow passing props all the way down to component that should handle 'as'.
    • have something like deleteProps on 'styled-component' core component to do tag cleanup build in library. tag.* by default for us is cleaning both defaultBlacklist and blacklist.
  21. diondiondion commented on Jan 22, 2019

    @diondiondion
    Author

    The astroturf library solves this issue by allowing to specify an allowAs option like this:

    const StyledFooter = styled(Footer, { allowAs: true })`
      color: red;
    `

    Looks clean and does the job.

  22. kizu commented on Mar 25, 2019

    @kizu

    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 as seems 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 as prop itself, styled-components would just pass as to 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 as prop 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 the as prop by itself.

    In my practice you never want to redefine the component via as when used with styled(MyComponent), but in most cases you want to do so with styled.div etc.

  23. stonebk commented on Aug 28, 2019

    @stonebk

    @diondiondion what do you think of this proof of concept API: #2448 (comment)

  24. diondiondion commented on Aug 28, 2019

    @diondiondion
    Author

    what do you think of this proof of concept API: #2448 (comment)

    @stonebk I wouldn't be too fond of it as an official API. forwardRef is 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 as and pass it on like the other props, and without messing up the built-in ref forwarding.

    Something like the astroturf API linked to above would be perfect IMO.

  25. stonebk commented on Aug 28, 2019

    @stonebk

    what do you think of this proof of concept API: #2448 (comment)

    @stonebk I wouldn't be too fond of it as an official API. forwardRef is 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 as and pass it on like the other props, and without messing up the built-in ref forwarding.

    Something like the astroturf API linked to above would be perfect IMO.

    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.

  26. abutterworth commented on Apr 16, 2021

    @abutterworth

    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 as prop (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 wherever as is currently used in the code base we get (mildly) unexpected behavior. How do we adopt styled-components without asking everyone to update their usages of as to forwardedAs.

    A solution

    A forwardAsProp HOC:

    import React from 'react';
    
    // This HOC moves the as prop to the forwardedAs prop for use with styled-components.
    // This function could be reworked into some generic redirectProp HOC, but since
    // this is the only current use case, we'll leave it specific to as -> forwardedAs
    // and save the extra code/processing.
    // Others with the issue that this solves:
    // - https://github.com/reakit/reakit/issues/226
    // - https://github.com/styled-components/styled-components/pull/3006#issuecomment-587415822
    // eslint-disable-next-line react/prop-types
    const forwardAsProp = Component => ({ as, ...props }) => (
      <Component
        forwardedAs={as}
        {...props}
      />
    );
    
    export default forwardAsProp;
    

    Usage in a Button component in the component library:

    import styled from 'styled-components';
    import RBButton from 'react-bootstrap/Button';
    import forwardAsProp from '../utils/forwardAsProp';
    
    const Button = forwardAsProp(styled(RBButton)`
      border: 2px solid palevioletred;
    `);
    
    export default Button;
    

    The end result is no disruptive change for consumer of the component library.

  27. kitten commented on Aug 9, 2021

    @kitten
    Member

    There's several workarounds to this, so given a lack of activity and attrs supporting "as", I'll go ahead and close this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions