Guilherme
Guilherme

Reputation: 15

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;

Upvotes: 0

Views: 365

Answers (1)

Hakim Abdelcadir
Hakim Abdelcadir

Reputation: 1326

Create the ButtonForwarded component like this:

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

Upvotes: 2

Related Questions