Skip to content

Instantly share code, notes, and snippets.

@ChrisDobby
Created July 30, 2019 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisDobby/20fec6c834443ada50511284bd21a2c1 to your computer and use it in GitHub Desktop.
Save ChrisDobby/20fec6c834443ada50511284bd21a2c1 to your computer and use it in GitHub Desktop.
Example of React component in Typescript using a callback to set a ref
import * as React from "react";
class CallbackRef extends React.Component {
divRef: HTMLDivElement | null = null;
setDivRef = (element: HTMLDivElement) => {
this.divRef = element;
};
componentDidMount() {
if (this.divRef) {
console.log(`callbackRef div width: ${this.divRef.clientWidth}`);
}
}
render() {
return <div ref={this.setDivRef} style={{ width: "100%", height: "30px", backgroundColor: "red" }} />;
}
}
export default CallbackRef;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment