Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does React.createRef() for material-ui Button element in TypeScript not work correctly?

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?

like image 860
ChrisP Avatar asked Aug 13 '20 18:08

ChrisP


People also ask

How do you use createRef in react?

Starting from React 16.3, the React API included a createRef() method that can be used for creating refs in much the same way as we did using the callback function. You simply create a ref by calling React. createRef() and assign the resulting ref to an element.

What is ref in button?

The ref is created in the constructor and then attached to the input element when it renders. When the button is clicked, the value submitted from the input element (which has the ref attached) is used to update the state of the text (contained in an H3 tag).

How do refs react to elements?

In order to get a reference to a React component, you can either use this to get the current React component, or you can use a ref to get a reference to a component you own. They work like this: var MyComponent = React. createClass({ handleClick: function() { // Explicitly focus the text input using the raw DOM API.

What is ref prop in react?

Refs are a function provided by React to access the DOM element and the React element that you might have created on your own. They are used in cases where we want to change the value of a child component, without making use of props and all.


1 Answers

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} />
);
like image 198
keemor Avatar answered Oct 08 '22 13:10

keemor