Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between `PropTypes.node` and `PropTypes.any` in react?

// Anything that can be rendered: numbers, strings, elements or an array // (or fragment) containing these types. optionalNode: PropTypes.node,  // A value of any data type requiredAny: PropTypes.any.isRequired, 

Which types does PropTypes.any contain compared to PropTypes.node?

like image 400
yingting nie Avatar asked May 07 '18 03:05

yingting nie


People also ask

What is the use of PropTypes in React?

PropTypes are simply a mechanism that ensures that the passed value is of the correct datatype. This makes sure that we don't receive an error at the very end of our app by the console which might not be easy to deal with.

What is the PropTypes for a React component?

PropTypes is React's internal mechanism for adding type checking to components. React components use a special property named propTypes to set up type checking. When props are passed to a React component, they are checked against the type definitions configured in the propTypes property.

What is the difference between flow and PropTypes?

Flow is a static analysis tool which uses a superset of the language, allowing you to add type annotations to all of your code and catch an entire class of bugs at compile time. PropTypes is a basic type checker which has been patched onto React.

Is PropTypes necessary in React?

One of the most important things when building React application is to make sure that the components receive correct props. Passing wrong props leads to bugs and unexpected behavior, so it's a good idea to warn developers about this as early as possible.


2 Answers

PropTypes are a way to validate the values that are passed in through our props.

node We can pass anything that can be rendered, such as numbers, string, DOM elements, arrays, or fragments that contain them using the React.PropTypes.node.

any type React allows us to specify that a prop must be present, regardless of it's type. We can do this by using the React.PropTypes.any validator.

like image 191
Priya Avatar answered Sep 29 '22 19:09

Priya


PropTypes.node: any render-able value like numbers and string, that can actually be rendered on screen.

PropTypes.any: any type of value, even those are non-render-able like boolean.

Incase of <div>{true}</div> JSX code,

booleanValue: PropTypes.node will give an error, while booleanValue: PropTypes.any will not give any such error.

like image 45
Nitin Jadhav Avatar answered Sep 29 '22 19:09

Nitin Jadhav