Skip to content

Disable automatic passing down of props #135

Closed

Description

@timsuchanek

Version

1.0.5

Steps to reproduce

    import { Link } from 'react-router'

    const ListElement = styled(Link)`

      ${props => props.active && activeListElement}
    `

Expected Behavior

Work without warnings

Actual Behavior

screen shot 2016-10-24 at 1 55 05 pm

Is it possible to disable the automatic pass down of props so we don't have that warning anymore?

Thanks!

Activity

  1. vdanchenkov commented on Oct 25, 2016

    @vdanchenkov
    Member

    Do you mean some props selectively? I'd suggest:

    const ListElement = styled(({ active, ...rest }) => <Link {...rest} />)`
  2. timsuchanek commented on Oct 25, 2016

    @timsuchanek
    Author

    Yes indeed. Nice solution, thanks!

  3. timsuchanek commented on Oct 26, 2016

    @timsuchanek
    Author

    As we are using typescript and it doesn't yet support the spread operator in objects, thats my solution right now:

    export function ExcludeProps(SubComponent: any, filter: string[] = []) {
      return (props) => {
        const keys = Object.keys(props).filter(key => !filter.includes(key))
        const picked = lodash.pick(props, keys)
    
        return <SubComponent {...picked} />
      }
    }

    @mxstbr Maybe we should write an official statement into the docs as other people could encounter a similiar problem with the new react version?

  4. mxstbr commented on Oct 30, 2016

    @mxstbr
    Member

    Hmm, that's an issue with out validAttrs.js util – it seems to let that one pass through, even though it's invalid.

  5. vdanchenkov commented on Oct 31, 2016

    @vdanchenkov
    Member

    @mxstbr This issue is about styling 3-rd party components. I believe that you want to pass all the props unfiltered in this case.

  6. mxstbr commented on Oct 31, 2016

    @mxstbr
    Member

    Ah yeah, true – I think this is actually expected behaviour here, you're right! I'll close this for now since @vdanchenkov's solution works fine and we can't really do anything from our side to fix this. Cheers!

  7. iamthesiz commented on Sep 26, 2017

    @iamthesiz

    I did mine like this.

    import { withRouter } from 'react-router-dom'
    import styled from 'styled-components'
    
    
    export const Link = withRouter(({ to, history, onClick = null, ...props }) =>
    	<Base {...props} onClick={e => onClick ? onClick(e) : history.push(to)} />
    )
    
    const Base = styled.a`
    	cursor: pointer;
    	text-decoration: none;
    `
    
  8. joetidee commented on Apr 28, 2018

    @joetidee

    What about if you are extending a component? In the example below, I want completed to be accessed by StyledItemTextarea but not Textarea.

    import Textarea from 'react-textarea-autosize';
    
    const TextareaAutosizeSC = styled(Textarea)`
        ...
    `;
    
    const StyledItemTextarea = TextareaAutosizeSC.extend`
        color: ${({ completed }) => completed ? '#ccc' : '#fff'};
    `;
    
  9. nicgirault commented on Jun 27, 2018

    @nicgirault
    const ListElement = styled(({ active, ...rest }) => <Link {...rest} />)`

    works fine (although the syntax highlighting is broken on vscode). However it creates an anonymous component that makes it harder to navigate in the virtual DOM and read a stacktrace. Naming the component is much more verbose and does not solve the indent in the virtual DOM so I would support an option to intercept props.

    With a very naïve approach I would like to be able to write something like:

    const ListElement = styled(Link, {intercept: ['active']})`
  10. janosh commented on Jan 4, 2019

    @janosh

    Any comments from maintainers regarding @nicgirault's proposal? Something along those lines would be nice to have!

  11. alansouzati commented on Jan 18, 2019

    @alansouzati
    Contributor

    I'm facing this problem too. I don't think const ListElement = styled(({ active, ...rest }) => <Link {...rest} />) is bullet proof solution. Here is where it is failing for me:

    1) Callers can pass as prop and now the component suddenly breaks. for example:

    <ListElement as="span" />
    

    One would expect that it would render a Link as a span tag, but it gets rid of the Link altogether. Don't get me wrong, this is the expected behavior in styled-components, but it makes it difficult customize things. I had to introduce a tagName prop just for that. And I keep getting the question why you need "tagName" since styled-components has "as" prop?

    2) Hard, if not impossible to extend styles.

    I have a Box component with some styles. This Box has a color prop that I need to exclude (otherwise it will bleed). Now I want a Flex component that augments this Box with flexbox capabilities. This Flex has a direction prop that I need to exclude. For example:

    const Box = styled(({ color, ...rest}) => <div {...rest} />)`
      color: ${props => props.color};
    `;
    
    const Flex = styled(Box)`
      flex-direction: ${props => props.direction};
    `;
    

    Now if you inspect the DOM Box color does not bleed, but Flex direction does. I'm failing to identify how to properly extend these styles.

    3) Having to deal with forwardRef and increasing the React DOM Tree.

    Since I'm adding ({ active, ...rest }) => <Link {...rest} /> forward refs don't work anymore. Meaning <ListElement ref={React.createRef()} />the ref will be the React element instead of the actual DOM, forcing me to use a deprecated findDOMNode API. Or wire the forwardRef which increases the React Depth Tree (which brings performance issues in React dev env)

    I feel that everything would be much easier if styled-component allowed an API to exclude props to bleed to the DOM:

    const Box = styled("div", { excludeProps: ['color'] })`
      color: ${props => props.color};
    `;
    
    const Flex = styled(Box, { excludeProps: ['direction'] })`
      flex-direction: ${props => props.direction};
    `;
    
  12. 5 remaining items

  13. JamesBliss commented on Apr 17, 2019

    @JamesBliss

    @tomspeak I've found these:

    A v5 Roadmap #1934 which links to issue #2093 but nothing still seems defined, decided or clear.

  14. JamesBliss commented on Apr 17, 2019

    @JamesBliss

    @tomspeak and anyone else... here is an example of how it could be bypassed as an issue. Although this solution would be very hard to get a team to understand and stick too. codesandbox example!

  15. rtymchyk commented on Apr 18, 2019

    @rtymchyk

    This is very annoying when trying to make components with AMP :)

  16. Alappin commented on Apr 22, 2019

    @Alappin

    A temporary clean work around.

    
    import styled from 'styled-components';
    import omit from 'lodash/omit';
    
    const withFilter(Tag, filter = []) => {
    	return props => <Tag {...omit(props, filter)} />;
    };
    
    const Tag = ...;
    
    const StyledTag = styled(withFilter(Tag, ['color'])`
      color: ${props => props.color}
    ` 
    

    Skipping the filter array will just gracefully work. I guess the ideal solution in the future would just allow the second parameter to be used for filtering as others have already suggested in the thread above.

  17. nkov commented on May 8, 2019

    @nkov

    Another workaround is to use data-* attributes, for which the DOM doesn't throw warnings.

  18. nathggns commented on Jul 31, 2019

    @nathggns

    I don't think this issue should be closed. I'm very much still running into this issue, and it seems unfortunate that the proper way to avoid this problem is to add a wrapper component.

  19. Zerquix18 commented on Aug 8, 2019

    @Zerquix18

    +1 ??

  20. jdfm commented on Aug 12, 2019

    @jdfm

    @alansouzati excludeProps makes me think that the prop will not be available, so, when writing out the CSS my expectation is that it's not there for our use. How about captureProps instead?

  21. rtymchyk commented on Aug 22, 2019

    @rtymchyk

    A temporary clean work around.

    This is good but but omit is being dropped for performance reasons from Lodash.

    Here's a variation:

    import React from 'react'
    import PropTypes from 'prop-types'
    import pickBy from 'lodash/pickBy'
    
    export default function omitProps(Component, propsToOmit) {
      function isAllowedProp(_, prop) {
        return !propsToOmit.includes(prop)
      }
    
      function WithoutOmittedProps({ children, ...rest }) {
        const withOmittedProps = pickBy(rest, isAllowedProp)
        return <Component {...withOmittedProps}>{children}</Component>
      }
    
      WithoutOmittedProps.propTypes = {
        children: PropTypes.node,
      }
    
      WithoutOmittedProps.displayName = `WithoutOmittedProps(${Component.displayName || Component.name || Component})`
    
      return WithoutOmittedProps
    }
  22. 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.

  23. random1911 commented on Nov 17, 2019

    @random1911

    Hey guys.
    What about made new API similar to Emotion - https://emotion.sh/docs/styled#customizing-prop-forwarding - that shouldForwardProp really helpfull with damn styling

  24. SimonSomlai commented on Apr 27, 2020

    @SimonSomlai

    Here's a simple typescript solution that worked for me;

    interface LinkProps {
      to: string;
    }
    
    interface SidebarLinkProps extends LinkProps {
      active: boolean;
    }
    
    const SidebarLink = styled(({ active, ...rest }: SidebarLinkProps) => (
      <RouteLink {...rest} />
    ))`
      color: red;
      ${({ active }) => active && `color: green`}
    `;
  25. avxkim commented on Apr 29, 2020

    @avxkim

    @SimonSomlai how do you type <RouteLink />'s children? I'm just getting an error: type '{ children: string; }' has no properties in common with type

  26. ankitsny commented on Aug 27, 2020

    @ankitsny

    You can use transient props, Checkout this docs

    https://styled-components.com/docs/api#transient-props
    https://styled-components.com/docs/api#shouldforwardprop

    import styled from "styled-components";
    
    const StyledInput = styled(Input).withConfig({
      shouldForwardProp: (prop, defPropValFN) =>
        !["rounded", "redColor"].includes(prop) && defPropValFN(prop),
    })`
      border: 1px solid ${(props) => props.theme.sColor || props.theme.pColor};
      color: ${(props) => props.theme.pColor};
      ${(props) => (props.rounded ? "border-radius: 20px" : "")};
      ${({ redColor }) => (redColor ? "color: red" : "")};
    `;
  27. jonatassales commented on Mar 23, 2021

    @jonatassales

    Created a solution based on what @anks333 did:

    import { StyledConfig } from 'styled-components'
    
    export default function omitForwardedProps<PropType extends {}>(props: string[]): StyledConfig<PropType> {
      return {
        shouldForwardProp: (prop, defPropValFN) => !props.includes(prop.toString()) && defPropValFN(prop)
      }
    }

    ...

    import styled from 'styled-components'
    import Typography, { TypographyProps } from '@material-ui/core/Typography'
    
    import { omitForwardedProps } from '@infra/styled-components/utils'
    interface BreadcrumbItemProps extends TypographyProps {
      highlighted?: boolean
    }
    
    export const BreadcrumbItem = styled(Typography).withConfig(
      omitForwardedProps<TypographyProps>(['highlighted'])
    )<BreadcrumbItemProps>`
      color: ${({ highlighted, theme }) => (highlighted ? theme.colors.primary : theme.colors.black)};
      font-size: ${({ theme }) => theme.fontSizes.headline6};
      white-space: nowrap;
    `
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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions