milesj / babel-plugin-typescript-to-proptypes

Generate React PropTypes from TypeScript interfaces or type aliases.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Does not work with forwardRef

LankyLou opened this issue · comments

When using React.forwardRef, the proptypes are not generated.

@LankyLou Are you doing something like this?

const Comp = React.forwardRef();

Comp.propTypes = {};

I'm doing something like this:

const Comp = forwardRef((props, ref) => { /* … */ });
Comp.displayName = "Comp";
Comp.defaultProps = { /* … */ };
export default Comp;

I'm not sure how to support this properly since half the time there isn't any type information for the props, for example.

const RefComp = React.forwardRef((props, ref) => <OtherComp ref={ref} {...props} />);

The types are usually defined on OtherComp, which can be located anywhere. This seems like a feature that'll require the type checker.

@milesj Is there a way to hint the proper type for the props so that the plugin can manually generate prop types for situations like this? Something like:

type CompProps = { foo: string };
const Comp = forwardRef<HTMLDivElement, CompProps>((props, ref) => { /* … */ });
/* babel-plugin-typescript-to-proptypes ["Comp", "CompProps"] */
Comp.displayName = "Comp";
Comp.defaultProps = { /* … */ };
export default Comp;

So the plugin can skip attempts at finding the Comp component and CompProps type, and just output something like Comp.propTypes = { foo: PropTypes.string };?

P.S. Sorry I forgot to write that earlier example as Typescript

@vdh Yeah, that's about the only solution at the moment.

This should work now.

@milesj Thanks for this, it works great for me now

@milesj Is there a way to hint the proper type for the props so that the plugin can manually generate prop types for situations like this? Something like:

type CompProps = { foo: string };
const Comp = forwardRef<HTMLDivElement, CompProps>((props, ref) => { /* … */ });
/* babel-plugin-typescript-to-proptypes ["Comp", "CompProps"] */
Comp.displayName = "Comp";
Comp.defaultProps = { /* … */ };
export default Comp;

So the plugin can skip attempts at finding the Comp component and CompProps type, and just output something like Comp.propTypes = { foo: PropTypes.string };?

I can't seem to get this to work with forwardRef.
Is there a specific line i need to add? I noticed in your tests you named the type RefProps, which didn't seem to work.
/* babel-plugin-typescript-to-proptypes ["Comp", "CompProps"] */ is this needed?
are defaultProps needed?
Is there an example somewhere of how to write forwardRef with typescript to get the proptypes to work?

Thanks, that helped!