Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does React warn of additional props that a component wasn't expecting?

If I pass the prop bar to the component below, will React throw a warning/error?

class MyComponent extends Component {
  ...
}

MyComponent.PropTypes = {
  foo: PropType.string,
};
like image 417
JoeTidee Avatar asked Feb 09 '18 12:02

JoeTidee


People also ask

How many props are too many React?

I follow this rule of thumb: Three props is fine. Five props is a code smell. More than seven props is a disaster.

What happens when props change React?

React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically.

Is not a prop trying to access it will result in undefined being returned?

The warning " key is not a prop. Trying to access it will result in undefined being returned" is caused when we try to access the key prop of a component in React. To solve the error, pass a prop with a different name to your component.

Are React props passed by reference?

Short answer: props are passed by reference. The reason it can be confusing: if you change the parent's state by hand (bad practice!), the object will change in the child component, too. But won't trigger re-render! (The child component won't "know" that its props has changed.)


Video Answer


1 Answers

No, it only warns you when you pass a prop defined in propTypes that does not have the expected type.

If you want to be warned about this, you can use the custom Airbnb implementation of the prop-types package that includes a validator forbidExtraProps.

You also have a typo in your example code. The proptypes object on your component needs to start with a lower-case p to make it work:

MyComponent.propTypes = {
  foo: PropTypes.string,
};
like image 166
trixn Avatar answered Oct 07 '22 18:10

trixn