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.
What needs to be changed to correct this error?
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.
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).
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.
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.
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} />
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With