Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify null prop type in ReactJS?

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} /> 
like image 400
user1261710 Avatar asked Nov 21 '16 21:11

user1261710


People also ask

What is type of null in React JS?

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!

How do you assign a prop to type in React?

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.

How do you define a default prop in React?

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.

How do you pass optional props in React?

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.


Video Answer


1 Answers

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.

like image 53
Lars Nyström Avatar answered Sep 21 '22 13:09

Lars Nyström