Skip to content

"Warning: Unknown props" when wrapping an external component #305

Closed

Description

@kitze

I have this styled-component:

import FontAwesome from 'react-fontawesome';

export const Icon = styled(FontAwesome)`
  font-size: 25px;
  margin-bottom: 3px;
  ${props => props.active && `color: ${props.colors.brand}`}
`;

Which is wrapping FontAwesome which is an external component.

I'm passing active and colors as props but the component complains that they are unknown.

Activity

  1. vdanchenkov commented on Dec 10, 2016

    @vdanchenkov
    Member

    Styled components pass props to the underlying component by design. You would get same results with

    <FontAwesome active={} colors={}/>

    Problem is that FontAwesome passes all unknown props to the DOM element.

    One solution is to filter props manually

    export const Icon = styled(({ active, colors, ...rest }) => <FontAwesome {...rest} />)
  2. k15a commented on Dec 10, 2016

    @k15a
    Member

    How about something similar to this: #291 (comment)

    import styled from 'styled-components'
    import FontAwesome from 'react-fontawesome'
    
    export const Icon = styled(FontAwesome)`
      font-size: 25px;
      margin-bottom: 3px;
      ${props => props.active && `color: ${props.colors.brand}`}
    `
    
    Icon.passProps = false

    or

    import styled from 'styled-components'
    import FontAwesome from 'react-fontawesome'
    
    export const Icon = styled(FontAwesome).passProps(false)`
      font-size: 25px;
      margin-bottom: 3px;
      ${props => props.active && `color: ${props.colors.brand}`}
    `
  3. diegohaz commented on Dec 10, 2016

    @diegohaz
    Member

    @k15a

    I like it, but most third party components need some custom props. It should be something like this:

    export const Icon = styled(FontAwesome).passProps({ active: false, colors: false })``

    We can also use propTypes to identify the props that belong to Icon, and not FontAwesome.

    export const Icon = styled(FontAwesome)``
    
    Icon.propTypes = {
      active: PropTypes.bool,
      colors: PropTypes.object
    }

    It will not work if one strips propTypes as part of build process using something like babel-plugin-transform-react-remove-prop-types though.

  4. k15a commented on Dec 10, 2016

    @k15a
    Member

    You could also combine both and allow false to pass no props and a object which will whitelist / blacklist (which one should be decided) props.

  5. diegohaz commented on Dec 10, 2016

    @diegohaz
    Member

    That passProps would be very useful. I currently have some duplicated code with @vdanchenkov's solution

    e.g. A Button that renders a MenuButton from react-aria-menubutton or a Link from react-router

    const StyledMenuButton = styled(({ disabled, transparent, light, kind, size, ...props }) =>
      <MenuButton {...props} />
    )`${styles}`
    const StyledLink = styled(({ disabled, transparent, light, kind, size, ...props }) =>
      <Link {...props} />
    )`${styles}`

    It could be simplified with something like passProps:

    const propsToPass = { disabled: false, transparent: false, light: false, kind: false, size: false }
    const StyledMenuButton = styled(MenuButton).passProps(propsToPass)`${styles}`
    const StyledLink = styled(Link).passProps(propsToPass)`${styles}`
  6. diegohaz commented on Dec 10, 2016

    @diegohaz
    Member

    Another issue complaining about it: #135

  7. k15a commented on Dec 10, 2016

    @k15a
    Member

    I will probably look into this and #291 tomorrow if nobody else will solve this.

  8. mxstbr commented on Dec 13, 2016

    @mxstbr
    Member

    I think we will need to get rid of our attributes whitelist anyway one day, so we'll need an API like is being discussed here but that requires a lot more considerations than just solving this one use case.

    I'll close this issue for now as I don't think we'll do this in the very near future, but I appreciate all the comments here and we'll definitely use this as a basis for the next discussion about this!

  9. aesopwolf commented on Dec 15, 2016

    @aesopwolf

    @mxstbr I know it's only been 2 days since you closed this, but I'd really like to open it up back up.

    What do you think about encouraging users to pass a prop called inputProps separately, and apply it instead?

    For example:

    render() {
      const { theme } = this.state
    
      return <Component theme={theme} {...this.props.inputProps} />
    }
  10. manolkalinov commented on Dec 23, 2016

    @manolkalinov

    I read the thread, but am still at a loss as to whether something like FontAwesome can be used with styled-components right now. And if yes, is there an example piece of code I can look at?

  11. timmeade commented on Jan 8, 2017

    @timmeade

    Just adding my bit to this. Would be very nice to have.

    I created a NavItem which is a styled link. I was using a prop to identify to put a left bar on it:

    border-left: 1px solid ${props => props.leftBar ? darkBorder : 'transparent'};

    but the underlying link is kicking out the unknown props leftBar warning.

    I guess I'll just create several NavItem components styled each way to clear the warnings.

  12. barbalex commented on Jan 18, 2017

    @barbalex

    This is completely erroring up the console in my project as I need to pass many props to influence styling :-(

    @vdanchenkov: I don't get how your proposal would work to style a complicated component that has a whole bunch of children: In this case I would have to define the entire jsx outside of the render component and inside the styled function? Or did I get something wrong?

  13. vdanchenkov commented on Jan 18, 2017

    @vdanchenkov
    Member

    @barbalex My proposal helps to overcome problematic components putting all the props on the root dom element. Like this const Comp = ({props}) => <div {...props}>{props.text}</div>. If you have control over components source code - best way is to not design components this way.

    Do not do <div {...props}/> and there will be no need in this workaround.

  14. barbalex commented on Jan 19, 2017

    @barbalex

    o.k., got it: the reason @vdanchenkov 's solution did not work for me was:

    • object spread does not work when stage-0 is preset. I also needed to preset es2015 and install "transform-es2015-destructuring" and "transform-object-rest-spread" plugins
    • I am using electron-react-boilerplate. It includes tcomb which would not accept the way @vdanchenkov 's solution is written

    After making babel happy and uninstalling tcomb it works nicely now.

    Thanks all for a great tool and your help!

  15. barbalex commented on Jan 19, 2017

    @barbalex

    oh, just in case other people want to see a complete example (which I missed):

    const Field = styled(({ isPrintPreview, children, ...rest }) => <div {...rest}>{children}</div>)`
      height: ${(props) => (props.isPrintPreview ? '17px' : 'auto')};
      input {
        font-size: ${(props) => (props.isPrintPreview ? '10px' : 'inherit')};
      }
    `
    
  16. rjhilgefort commented on Feb 7, 2017

    @rjhilgefort

    This is a bit of a bummer. Thanks to @vdanchenkov and @barbalex for your examples on a work around. While it works, it promotes having to ignore eslint's no-unused-vars rule. I really dislike having to make exceptions every time I need to leverage this pattern.

    This is a pretty basic use case when considering react-router's Link component- is there a less hacky way to work around the issue? For anyone curious, here's another example (which is exactly @barbalex's example, but using the Link component):

    // eslint-disable-next-line no-unused-vars
    const FooterLink = styled(({ left, right, children, ...rest }) => (
      <Link {...rest}>{children}</Link>
    ))`
      display: inline-block;
      ${({ left }) => (left ? 'float: left;' : '')}
      ${({ right }) => (right ? 'float: right;' : '')}
    `;
  17. diegohaz commented on Feb 7, 2017

    @diegohaz
    Member
  18. rjhilgefort commented on Feb 7, 2017

    @rjhilgefort

    @diegohaz thanks for the heads up. I still think it's a bit strange for this to be the accepted pattern for situations like this.

  19. jole78 commented on Feb 20, 2017

    @jole78

    While we're waiting for v2 (which will hopefully solve this) I've used this approach which works fine and doesn't pollute the code so much I think. I'll share it so other can maybe benefit.
    It used lodash omit to "strip" the custom props (in the example 'direction' and 'align-items') used by the styled component and then happily send the other ones down the chain.

    import React from "react";
    import styled from "styled-components";
    import {omit} from 'lodash';
    
    const FlexBox = styled((props) => <div {...omit(props, FlexBox.OmitProps)} />)`
    	display: flex;
    	flex-direction: ${props => props.direction};
    	align-items: ${props => props['align-items']};
    `;
    
    FlexBox.OmitProps = [
        'direction',
        'align-items'
    ]
    
    FlexBox.defaultProps = {
        direction: "row",
        'align-items': "stretch"
    };
    
    FlexBox.propTypes = {
        direction: React.PropTypes.oneOf(["row", "column"]),
        'align-items': React.PropTypes.oneOf(["flex-start", "flex-end", "center", "baseline", "stretch"])
    };
    
    export default FlexBox;
  20. timscott commented on May 2, 2017

    @timscott

    Here's a reusable implementation of the workaround offered by @diegohaz and others:

    const swallowingStyled = (WrappedComponent, {swallowProps = []} = {}) => {
      const Wrapper = ({children, ...props}) => {
        swallowProps.forEach(propName => {
          delete props[propName];
        });
        return <WrappedComponent {...props}>{children}</WrappedComponent>;
      };
      return styled(Wrapper);
    };

    Used like so:

    const Card = swallowingStyled(Paper, {swallowProps: ['samplesMode']})`
      margin: 0 10px 10px 0;
      padding: 10px;
      flex-flow: ${({samplesMode}) => samplesMode && 'column'};
    `; 
  21. chrisknu commented on May 3, 2017

    @chrisknu

    @jole78 omit works well and is extensible!

  22. MatthieuLemoine commented on May 4, 2017

    @MatthieuLemoine
    Member

    Using Proxy you can do something like that in a styled.js file :

    import React from 'react';
    import styled from 'styled-components/native';
    import * as RN from 'react-native';
    
    const handler = {
      // Handle styled.tag
      get : (target, name) => (...args) => (...omitProps) => {
        const Wrapped = ({ children, ...props }) => {
          omitProps.forEach(prop => delete props[prop]);
          const WrappedComponent = RN[name];
          return <WrappedComponent {...props}>{children}</WrappedComponent>;
        };
        return target(Wrapped)(...args);
      },
      // Handle styled(Component)
      apply : (target, _, [WrappedComponent]) => (...args) => (...omitProps) => {
        const Wrapped = ({ children, ...props }) => {
          omitProps.forEach(prop => delete props[prop]);
          return <WrappedComponent {...props}>{children}</WrappedComponent>;
        };
        return target(Wrapped)(...args);
      },
    };
    
    const proxy = new Proxy(styled, handler);
    
    export default proxy;

    And then use styled instead of styled-components :

    import styled from 'styled';
    
    const Container = styled.View``;
  23. kitten commented on May 4, 2017

    @kitten
    Member

    I think this thread has long reached its limit. The rest of the discussions / suggestions should become - albeit the specific title - part of #439.

    There's several proposals on how to solve the whitelist props problem for both HTML and custom components in there, and it would be much appreciated if some more input would go there instead. Cheers!

  24. locked and limited conversation to collaborators on May 4, 2017
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