I\'m using Typescript with React. I\'m having trouble understanding how to use refs so as to get static typing and intellisense with respect to the react nodes referenced by
For typescript user no constructor required.
...
private divRef: HTMLDivElement | null = null
getDivRef = (ref: HTMLDivElement | null): void => {
this.divRef = ref
}
render() {
return <div ref={this.getDivRef} />
}
...
React.createRef
(class components)class ClassApp extends React.Component {
inputRef = React.createRef<HTMLInputElement>();
render() {
return <input type="text" ref={this.inputRef} />
}
}
Note: Omitting the old String Refs legacy API here...
React.useRef
(Hooks / function components)const FunctionApp = () => {
const inputRef = React.useRef<HTMLInputElement>(null) // note the passed in `null` arg
return <input type="text" ref={inputRef} />
}
Mutable refs for arbitrary stored values:
const FunctionApp = () => {
const renderCountRef = useRef(0)
useEffect(() => {
renderCountRef.current += 1
})
// ... other render code
}
Note: Don't initialize useRef
with null in this case. It would make the renderCountRef
type readonly (see example). If you need to provide null
as initial value, do this:
const renderCountRef = useRef<number | null>(null)
// Function component example
const FunctionApp = () => {
const handleDomNodeChange = (domNode: HTMLInputElement | null) => {
// ... do something with changed dom node.
}
return <input type="text" ref={handleDomNodeChange} />
}
Playground sample
Just to add a different approach - you can simply cast your ref, something like:
let myInputElement: Element = this.refs["myInput"] as Element