Search code examples
reactjsmobx-reactreact-proptypes

Is there a way to check propTypes for observer(Component)


For example, in this case, if I pass ObservedA to B as Comp:

const ObservedA = observer(class A extends React.Component {});

function B({Comp}) {
  return <Comp />;
}

B.propTypes = {
  Comp: PropTypes.node // Warning!
};

A warning occurs:

Warning: Failed prop type: Invalid prop Comp supplied to B, expected a ReactNode.

Is there a way to check propTypes for observer(Component)?


Solution

  • If you want to check if the Comp prop is a type that can be rendered, you can use PropTypes.elementType starting with prop-types 15.7.0:

    B.propTypes = {
      Comp: PropTypes.elementType
    };
    

    It will be valid for every renderable type, including e.g. context providers.