Sometimes, we may run into the ‘Unknown Prop Warning’ when developing React apps.
In this article, we’ll look at how to fix the ‘Unknown Prop Warning’ when developing React apps.
Fix the ‘Unknown Prop Warning’ When Developing React Apps
To fix the ‘Unknown Prop Warning’ when developing React apps, we should make sure that we’re passing in props to an element that are recognized as valid attributes.
For instance, if we have:
const Foo = (props) => {
  if (props.layout === 'horizontal') {
    return <div {...props} style={getHorizontalStyle()} />
  } else {
    return <div {...props} style={getVerticalStyle()} />
  }
}
Then we all the properties of props as props of the div element.
This means that the layout prop is also passed in as a prop of the div.
However, layout is not a valid attribute of the div, so we’ll get the ‘unknown prop’ warning in the console as a result.
To make sure we’re only passing in valid properties to the divs, we should destructure the props, we want to pass in.
For instance, we can write:
const Foo = ({ layout, ...rest }) => {
  if (layout === "horizontal") {
    return <div {...rest} style={getHorizontalStyle()} />;
  } else {
    return <div {...rest} style={getVerticalStyle()} />;
  }
};
to use the rest syntax to of the rest object that excludes the layout property.
Then we can spread the rest object properties as props of the div.
Assuming rest property names are all valid attribute names, we shouldn’t get the warning anymore.
Conclusion
To fix the ‘Unknown Prop Warning’ when developing React apps, we should make sure that we’re passing in props to an element that are recognized as valid attributes.
 
		
One reply on “How to Fix the ‘Unknown Prop Warning’ When Developing React Apps?”
Fantastic thank you for the article