4

As the document says here

array and object can be replaced with arrayOf and shape, respectively.

So, I did this in my project:

class X extends React.Component {
....
}

X.propTypes = {
    somePorp: PropTypes.shape.isRequired, // this cause an warnning in firefox, but satisfied eslint syntax check
    somePorp: PropTypes.object.isRequired, // no warnning in firefox, but can not satisfy eslint syntax check
}

Question:

How can I avoid warning message in firefox, as well as pass eslint syntax check (it's better no modification of eslint default rule)?

BTW: firefox warning is something like below

Warning: Failed prop type: X: prop type classes is invalid; it must be a function, usually from the prop-types package, but received undefined.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Hacksign
  • 416
  • 2
  • 7
  • 17

2 Answers2

4

You need to define the shape of the prop. If you're unsure, simply console.log() the prop and view it's make up. Click here to view the available PropType declarations.

For example, if you were to utilize redux store as this.props.store or history from react-router-dom as this.props.history:

enter image description here

history: PropTypes.objectOf(PropTypes.func).isRequired,       // object of funcs
store: PropTypes.shape({                                      // shape of...
  dispatch: PropTypes.func.isRequired,                          // func
  getState: PropTypes.func.isRequired,                          // func
  liftedStore: PropTypes.objectOf(PropTypes.func).isRequired,   // object of funcs
  replaceReducer: PropTypes.func.isRequired,                    // func
  subscribe: PropTypes.func.isRequired,                         // func
  Symbol: PropTypes.func.isRequired,                            // func
}).isRequired

Be careful when using isRequired, because sometimes the function/array/object/value/etc may or may not exist. For the example above, all of them should be present upon component mount.

Matt Carlotta
  • 18,972
  • 4
  • 39
  • 51
  • Thanks for quick reply;) there is 2 problems: 1. what if there is dynamic field(s) in shape definition? 2. what if there is nested object definition ? So, I guess the quickest resolution is enable object definition in .eslintrc rule file .... – Hacksign Nov 12 '18 at 05:58
  • 1
    It shouldn't matter if it's dynamic if it follows a similar pattern (like an array of objects, or array of funcs, array of strings...etc). If it doesn't follow a repeated pattern, then you'll either need to create a custom function (as shown at the bottom of the `usage` docs) or disable prop-type validation. – Matt Carlotta Nov 12 '18 at 06:10
0

You can also use the following way:

X.propTypes = {
    somePorp:  PropTypes.objectOf(PropTypes.object()),  
}
asmmahmud
  • 4,844
  • 2
  • 40
  • 47