Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PropTypes: array of one of the class instance

I am trying to give a type to one of my properties 'listOfItems'. I want this property to be an array of either instance of class 'Event' or instance of class 'Venue'. This is how I have implemented it:

MyClass.propTypes = {
 ...,
 listOfItems: PropTypes.arrayOf(PropTypes.oneOfType([
   PropTypes.instanceOf(Event),
   PropTypes.instanceOf(Venue)
]))

}

However, it doesn't seem to be working. I receive this warning: Failed prop type: Invalid prop listOfItems[0] of value [object Object] supplied to MyClass, expected one of [null,null].

I don't want to use PropTypes.shape to define array elements, as I will get quite an extended list of shape properties. This is what I mean:

MyClass.propTypes = {
 ...,
 listOfItems: PropTypes.arrayOf(PropTypes.shape({
  ... //list of properties
 }))
}

Please share your thought how would you define an array of objects with certain properties without writing each property of an object.

like image 404
Sveta Buben Avatar asked Jan 06 '18 16:01

Sveta Buben


2 Answers

You can try PropTypes.arrayOf(React.PropTypes.element) or using Shape is a good approach when comes to readability, you can easily understand what are the different types you can expect in that array.

like image 118
Ramya Velivala Avatar answered Oct 08 '22 06:10

Ramya Velivala


what fixed for me is to change oneOfType to oneOf, not sure if thats for your case as well.

like image 28
user2167582 Avatar answered Oct 08 '22 05:10

user2167582