Home > OS >  How to export a component attached to a component that uses React.forwardRef?
How to export a component attached to a component that uses React.forwardRef?

Time:02-02

I'm building a UI system for input components and I'm looking to attach a component to another component that needs to use forwardRef. It normally works when the forwardRef isn't being used but I'm currently getting the error below. How can I resolve this error, or is exporting a function in a forwardedRef component not allowed?

Error:

Property 'Secondary' does not exist on type 
'ForwardRefExoticComponent<ForwardedRefProps & RefAttributes<HTMLButtonElement>>'

Contrived Example

interface ButtonProps extends React.HTMLAttributes<HTMLButtonElement> {}

export const ForwardRefButton = React.forwardRef<HTMLButtonElement, ButtonProps>(
  function Button(props, ref) {
    return(
      <button ref={ref}>Ref is forwarded</button>
    )
  }
)

ForwardRefButton.Secondary = function () { // <- ForwardRefButton.Secondary errors
  return (
    <button>Secondary Button</button>
  )
}

CodePudding user response:

The error is occurring because you're trying to add a property Secondary to the ForwardRefButton component, which is a ForwardRefExoticComponent, which doesn't allow adding new properties to it.

One approach to resolve this issue is to wrap the ForwardRefButton in another component and add the property to that new component. For example:

interface ButtonProps extends React.HTMLAttributes<HTMLButtonElement> {}
export const ForwardRefButton = React.forwardRef<HTMLButtonElement, ButtonProps>(function Button(props, ref) {
  return(
    <button ref={ref}>Ref is forwarded</button>
  )
})

interface WrappedButtonProps extends ButtonProps {}
const WrappedButton = (props: WrappedButtonProps) => {
  return <ForwardRefButton {...props} />;
};
WrappedButton.Secondary = function () {
  return (
    <button>Secondary Button</button>
  )
};
export { WrappedButton as ForwardRefButton };
  • Related