'React | ForwardedRef using React.Component

I'm creating a custom component in React, and I need to export it using forwardedRef. But when I try, this error occurs:

error

my code:

export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement>{
  ref?: React.RefObject<HTMLButtonElement>;
}

class Button extends React.Component<ButtonProps> {

  render() {
    const {
      ref,
      children,
      ...otherProps
    } = this.props;
    return (
      <button 
        {...otherProps} 
        ref={ref}
      >
        {children}
      </button>
    )
  }
}

const ButtonForwarded = React.forwardRef<ButtonProps>((props, ref) => 
<Button {...props} ref={ref} /> );

ButtonForwarded.displayName = 'Button';

export default ButtonForwarded;


Solution 1:[1]

Create the ButtonForwarded component like this:

const ButtonForwarded = React.forwardRef((props: ButtonProps, ref: LegacyRef<Button>) => <Button {...props} ref={ref} /> );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1