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.
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 .
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!
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:
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