Search code examples
javascriptreactjstypescriptvisual-studio-codereact-proptypes

add prop types to render props function


When using regular react components, there are multiple ways to enable intellisense for a component (through prop types for functional componentds, or jsdoc comments), but if the component uses the render prop pattern like this:

return this.props.children({ config, onClickConfig })

and used like this:

<ConsumerComponent>
  {
    ({config, onClickConfig}) => (<button type="button" onClick={onClickConfig}>{config}</button>)
  }
</ConsumerComponent>

is there any way that we can enable intellisense for the type of the config object or the onClickConfig function ?

I see that typescript can enable this, by reusing the types in the consumer, but is it possible to achieve using jsdocs or prop types ?


Solution

  • My guess would be to use both and document well.

    const propTypes = {
      children: PropTypes.func.isRequired,
      // ... other proptypes
    }
    
    /**
     * @param {object} props the props object
     * @param {({ config: React.ElementType, onClickConfig: function }) => React.ElementType} props.children the render prop
     */
    const ConsumerComponent = ({ children, ...props }) => ( ..... );
    ConsumerComponent.propTypes = propTypes;