Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare a PropType corresponding to a nullable number?

I'm looking for a PropType that means

"this is required, and it will either be a number or be null"

In other words, what I have now is

PropTypes.number.isRequired 

but that throws a warning if a null value gets passed in, yet I want null to be an acceptable value.

like image 354
Ms. Corlib Avatar asked Jun 15 '16 18:06

Ms. Corlib


People also ask

How do you make a prop Nullable?

To specify null prop type in React, we can set null as the default prop value. We create the MyComponent component accepts the item prop. We set item 's type to be a string and is required. And then we specify that its default value is null so it can be set to null when nothing is set for item .

What is the type of null in React?

To check for null in React, use a comparison to check if the value is equal or is not equal to null , e.g. if (myValue === null) {} or if (myValue !== null) {} . If the condition is met, the if block will run. Copied!


1 Answers

Just use:

PropTypes.number 

By default all prop types aren't required (i.e. allow null or undefined) unless you pop a .isRequired on the end of them.

You can see the full docs for proptypes here:

  • https://reactjs.org/docs/typechecking-with-proptypes.html
like image 117
ctrlplusb Avatar answered Oct 13 '22 05:10

ctrlplusb