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,
};
I follow this rule of thumb: Three props is fine. Five props is a code smell. More than seven props is a disaster.
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.
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.
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.)
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,
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With