0

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;
1
  • Try to rename the ref property to some other name in the Button component. Commented Apr 17, 2022 at 17:34

1 Answer 1

2

Create the ButtonForwarded component like this:

const ButtonForwarded = React.forwardRef((props: ButtonProps, ref: LegacyRef<Button>) => <Button {...props} ref={ref} /> );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.