I've got a prop on a ReactJS Component that's either null or an Immutable Map.
At the bottom of my widget if I write:
MyComponent.propTypes = { myMap: React.PropTypes.instanceOf(Immutable.Map) };
I am leaving this open to the possibility of being null, undefined, or a Map.
How can I make this required and of type null or map only?
https://facebook.github.io/react/docs/typechecking-with-proptypes.html
I see this example but I do not know how to tailor the syntax to my needs or if it is even possible.
Edit: If a property is null, then it is still there but undefined means that it's not been included altogether.
For example:
<Component id={1} data={null} /> <Component id={2} data={Immutable.Map()} /> <Component id={3} />
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. App.js. Copied!
To run typechecking on the props for a component, you can assign the special propTypes property: import PropTypes from 'prop-types'; class Greeting extends React. Component { render() { return ( <h1>Hello, {this.props.name}</h1> ); } } Greeting. propTypes = { name: PropTypes.
The defaultProps is a React component property that allows you to set default values for the props argument. If the prop property is passed, it will be changed. The defaultProps can be defined as a property on the component class itself, to set the default props for the class.
To set optional props with default values in React TypeScript: Mark the props on the type as optional using a question mark. Provide default values for the props when destructuring them in the function's definition.
It is possible to use PropTypes.oneOf([null]).isRequired
. It should allow null, and nothing else. You can combine that with any other type:
PropTypes.oneOfType([ PropTypes.string.isRequired, PropTypes.oneOf([null]).isRequired, ]).isRequired
Edit: I just had this prop type fail for me when given a null prop using prop-types 15.7.2, so I'm not sure this works anymore (if it ever did?). I reverted to allowing both undefineds and nulls by just not using isRequired.
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