Creating strongly-typed refs in class components
In this lesson, we learn how to get a strongly-typed reference to an element in a class component.
We'll cover the following
Understanding createRef
#
In this lesson, we are going to implement the Search
component we implemented in the last lesson as a class component. Below is a first attempt:
class Search extends React.Component {
private input = React.useRef<HTMLInputElement>(null);
componentDidMount() {
if (this.input.current) {
this.input.current.focus();
}
}
render() {
return (
<form>
<input ref={this.input} type="type" />
</form>
);
}
}
What is wrong with this implementation?
Get hands-on with 1400+ tech skills courses.