7

Using React v16.13.1 I have the following component class with a Material-UI Button component and a RefObject to access the button element.

class Search extends React.Component<any, any>{

  constructor(props: any) {
    super(props)

    this.streetViewRef = React.createRef();
  }

  private streetViewRef: React.RefObject<Button>;
}

for the following Button element

<Button ref={this.streetViewRef} size="sm" variant="primary" block >Street View</Button>

However, the following TypeScript error is displayed.

enter image description here

What needs to be changed to correct this error?

1
  • looks like it may use forwardRef so the ref type is React.RefObject<HTMLButtonElement> but I'm not sure, that error message is not very clear, otherwise you probably wouldn't need to ask :) Aug 13, 2020 at 18:35

2 Answers 2

5

Take a look here https://www.selbekk.io/blog/2020/05/forwarding-refs-in-typescript/

The correct way to type a forwardRef component is:

type Props = {};
const Button = React.forwardRef<HTMLButtonElement, Props>(
  (props, ref) => <button ref={ref} {...props} />
);
0

You need to create ref with HTMLDivElement.

createRef<HTMLDivElement>()

So, this would be better.

private streetViewRef = createRef<HTMLDivElement>();
1
  • Using HTMLDivElement results in the same TypeScript error. Also seems like the RefObject should be typed to match the HTML element which is a Material UI button?
    – ChrisP
    Aug 14, 2020 at 15:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.