import React, { Component } from 'react'; class App extends Component<{}, {}> { // 1 - We need to declare a variable to hold our ref object canvasRef: React.RefObject; constructor(props: {}) { super(props); // 2 - We create an empty ref object and store it in our variable this.canvasRef = React.createRef(); } // Note: Normally, render() is put at the end of the component. // We show it here for this example because it fits better chronologically render() { // 3 - When we render, we attach the ref to the // Then - we return the to React for it to insert into the webpage return ( ); } componentDidMount() { // 4 - When the things we returned from render are added to the webpage by React, it will call componentDidMount() this.updateCanvasImage(); } updateCanvasImage() { // 5 - We can then access the canvas that was put into the webpage, to draw some content on it let canvas = this.canvasRef.current; if (canvas === null) return; // Canvas objects use a "graphics context" for drawing - so we need to get the "2d drawing" context // Canvases also support other kinds of drawing, like 3D, which is why they use contexts to separate them out let context = canvas.getContext("2d"); if (context === null) return; // Contexts work by setting up some fields on them (like the fill color - fillStyle), then calling methods context.fillStyle = "blue"; context.fillRect(50, 50, 150, 100); } } export default App;