4

I have a component wrapped with React.forwardRef and it so happens that it is a compound component as well.

I'm not sure how do I maintain

Form.Item = FormItem; 

while the Form component function being wrapped with forwardRef.

const Form = React.forwardRef((props, ref) => { return <form></form>}); 

Typescript gives me an error (rigthly) saying

Property 'Item' does not exist on type 'ForwardRefExoticComponent>'.ts(2339)

5
  • Can you modify Form component? Or is it from a third-party library? Commented Apr 1, 2020 at 10:08
  • I can modify my Form component Commented Apr 1, 2020 at 10:11
  • What about this - github.com/DefinitelyTyped/DefinitelyTyped/issues/… ? Commented Apr 1, 2020 at 10:12
  • It does seems relevant. Thanks! Commented Apr 1, 2020 at 10:18
  • See this repo and settle your issue. Commented Apr 1, 2020 at 10:36

2 Answers 2

3

Just to make it more clear of the solution, as it's on an external site (Credits to original author here, and thank you @Antoan Elenkov)

export interface Props = { ...yourPropsHere; }; export interface CompoundedComponent extends React.ForwardRefExoticComponent<Props & React.RefAttributes<HTMLInputElement>> { yourStaticFunctionOrSomethingLikeThat: () => void; } const Component = React.forwardRef<HTMLInputElement, Props>((props, ref) => ( <input ref={ref} {...props} /> )) as CompoundedComponent; Component.yourStaticFunctionOrSomethingLikeThat = () => {}; 
Sign up to request clarification or add additional context in comments.

3 Comments

Lack of reasoning by the author on why it works makes me hesitant to believe its better.
Regardless of "why it works", I would be very surprised if that was unstable/undefined behavior, as it's pretty much just Object.assign().
0

This solution from the same GH thread seems nicer to me:

const Form = React.forwardRef(function Form(...) { ... }) const FormItem = React.forwardRef(...) const FormNamespace = Object.assign(Form, {Item: FormItem}) export {FormNamespace as Form} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.