Refs in React provide access to DOM elements of a web page. Typescript has a type inference and Refs added to TSX, So we have to declare refs of a type HTMLInputElement or any DOM API type.
React Typescript refs example
This example explains adding focus to input box in react component. In Javascript, We used createRef() whic is a Generic funciton of any type.
inputRef = React.createRef();
In Typescript, Declare ref’s of type using Generic Syntax.
inputRef = React.createRef<HTMLInputElement>();
Adding the created inputRef
to input element using refs
attribute
<input type="text" ref={this.inputRef} />
Access the refs using this.inputRef.current and focus using focus() method.
this.inputRef.current?.focus()
Here is an complete example
import React, { Component } from 'react';
//props object
type AppProps={
counter:number;
}
//state object
type AppState={
message:string;
}
class First extends Component {
inputRef = React.createRef<HTMLInputElement>();
componentDidMount(){
this.inputRef.current?.focus()
}
render() {
return (
<div>
<input type="text" ref={this.inputRef} />
</div>
);
}
}
export default First;
Here is an Functional component createRef example
import React, { createRef } from 'react';
interface MessageProps{}
function Second(props:MessageProps){
const inputRef = createRef<HTMLInputElement>();
return (
<div>
<input type="text" ref={inputRef} />
</div>
);
};
export default Second;