reactjsreact-proptypes

Define propType for a html tag as well as a string in Props validation


I am trying to define proptype for a prop named label which receives two types of values sometimes a string or an html object such as <span>.I am trying to do it in different ways but I am failing to suppress the warnings.

Warning: Failed prop type: Invalid prop `label` supplied to `TextField`

Currently, I have done:

TextField.propTypes = {
  label: PropTypes.OneOfType([PropTypes.shape(PropTypes.object), PropTypes.string]).isRequired,
};

But it's not working. I don't want to use any.


Solution

  • If one of your props is an HTML element then you should use PropTypes.node instead of PropTypes.shape(PropTypes.object)

    Textfield.propTypes = {
      label: PropTypes.oneOfType([PropTypes.node, PropTypes.string]).isRequired
    };