Skip to content

Separate HTML attributes from styling props #439

Closed

Description

@jspangler

Background

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

screen shot 2017-01-31 at 11 31 51 am

Activity

  1. changed the title [-]Terminate props before passing to 3rd party[/-] [+]Separate HTML attributes from styling props[/+] on Jan 31, 2017
  2. mxstbr commented on Jan 31, 2017

    @mxstbr
    Member

    You hit upon a very interesting point there that @gaearon has been talking about and we've been thinking about.

    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)

  3. leonwilly commented on Feb 22, 2017

    @leonwilly

    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

    const Button = 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.

  4. jacobp100 commented on Feb 23, 2017

    @jacobp100
    Contributor

    See also: #403 #527. Should we close those bugs in favour of this?

  5. jacobp100 commented on Mar 1, 2017

    @jacobp100
    Contributor

    I meant close the others and keep this one open 😜

  6. bsbechtel commented on Mar 1, 2017

    @bsbechtel

    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?

  7. leonwilly commented on Mar 2, 2017

    @leonwilly

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

  8. jacobp100 commented on Mar 3, 2017

    @jacobp100
    Contributor

    Just to tie together comments in other threads, here are some ideas that were thrown around,

    Explicitly Define Props

    const Button = styled.div`
      ${bindProps("active", "primary", "secondary")}
      …
    `
    // Or
    const Button = styled.div`
      @properties active, primary secondary;
      …
    `
    // Or
    const Button = styled.div`…`
    Button.propTypes.active = PropTypes.bool;
    …

    Apply css-to-react-native to Style Props

    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.

    This won't actually work in RN.

  9. jacobp100 commented on Mar 4, 2017

    @jacobp100
    Contributor

    Interestingly, I just saw vue-styled-components, which seems to require knowing prop types upfront. They did it in the constructor.

    const modalProps = { isOpen: Boolean };
    
    const Modal = styled('div', modalProps)`
      display: ${props => props.isOpen : 'block' : 'none'}
    `;

    I think this is my favourite so far!

  10. bsbechtel commented on Mar 6, 2017

    @bsbechtel

    +1 for the vue-styled-components solution

  11. jacobp100 commented on Mar 6, 2017

    @jacobp100
    Contributor

    One more idea, which may be terrible, is to either pass in all styled props as a single prop,

    <Component styled={{ primary: 'red' }} passedProp={5} />

    Or require a prefix or suffix for styled props,

    <Component primaryStyle="red" passedProp={5} />

    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!

  12. geelen commented on Mar 7, 2017

    @geelen
    Member

    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:

    const Button = styled.Button`
        width: ${props => props.width ? (props.pop('width') - props.pop('padding')) + 'px' : '100%'};
    `
    <Button width={500} padding={16}/> // both popped
    <Button padding={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:

    const A = styled(Link).attrs({
      _include: 'href target'
    })`
      font-size: ${ props => props.large && '1.2em' };
      color: ${ props => props.red ? 'red' : 'black' };
    `
    <A href="#" large red/> // only 'href' passed through.
    
    
    const B = styled(Link).attrs({
      _exclude: 'large small red blue'
    })`
      ... same as A ...
    `
    
    <B href="#" large red/> // 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/Attributes
    const GLOBAL_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.

    const C = styled.div.attrs({
      x: props => props.y
    })`
      ${ props.z }
    `

    Of these, x is definitely being passed down to the div, but y and z are maybe not. Maybe they have defaults, maybe they have types? What about:

    C.props = {
      z: { pass: true, type: React.PropTypes.string, default: 'foo' },
      y: { type: React.PropTypes.string.isRequired }
    }

    Or something to that effect. Alternatively:

    import styled, { types } from 'styled-components'
    
    C.props = {
      z: types.string.passed.default('foo'),
      y: types.string.isRequired,
    }

    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!

  13. 191 remaining items

  14. topaxi commented on Nov 11, 2019

    @topaxi

    @hrasoa no, as soon as I provide an as prop, the component with the filtered props is no longer executed.

  15. hrasoa commented on Nov 11, 2019

    @hrasoa

    @topaxi yes this don't work with the "as" prop, you have to do the same in the switched component:

        as={props => <button {...filterProps(props)} />}
  16. lcswillems commented on Nov 15, 2019

    @lcswillems

    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:

    const StyledDiv = styled(({height, width, ...props}) => <div {...props} />)`
        width: ${props => props.width}px;
        height: ${props => props.height}px;
    `

    is turned into:

    const StyledDiv = styled.div(`
        width: ${props => props.width}px;
        height: ${props => props.height}px;
    `, ({width, height, ...props}) => props);

    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.

  17. wmertens commented on Nov 15, 2019

    @wmertens
    Contributor

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

  18. lcswillems commented on Nov 16, 2019

    @lcswillems

    That's true! So in this case, only:

    const StyledDiv = styled.div(props => `
        width: ${width}px;
        height: ${height}px;
    `, ({width, height, ...props}) => props);
    

    would work.

  19. ShanonJackson commented on Dec 29, 2019

    @ShanonJackson

    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.
  20. Steveeeie commented on Jan 3, 2020

    @Steveeeie

    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. 🤷‍♂

  21. flybayer commented on Jan 3, 2020

    @flybayer

    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:

    import styled from "styled-components"
    import css, { SystemStyleObject } from "@styled-system/css"
    
    interface StyleProps {
      sx?: SystemStyleObject
    }
    
    export const Box = styled.div<StyleProps>(props => css(props.sx))
    
    export const Text = styled.p<StyleProps>(props =>
      css({
        // Set some default styles
        fontSize: 1,
        mt: 0,
        mb: 3,
        lineHeight: 1.5,
        ...props.sx,
      })
    )
  22. martpie commented on Jan 14, 2020

    @martpie

    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.

  23. South-Paw commented on Jan 26, 2020

    @South-Paw

    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.

  24. wasinsandiego commented on Jan 28, 2020

    @wasinsandiego

    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

  25. penx commented on Feb 7, 2020

    @penx

    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?

  26. diondiondion commented on Feb 7, 2020

    @diondiondion

    As far as I'm aware, #2392 implements shouldForwardProp in the same way as emotion and would resolve this issue.

    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.

  27. karlhorky commented on Feb 9, 2020

    @karlhorky
    Contributor

    Thanks @stevesims for reopening the shouldForwardProp proposal in #3006 👍 Go upvote there!

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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions