Search code examples
reactjsreact-nativereact-componentkonvajskonvajs-reactjs

ref is null in ComponentDidMount


I have a ref to a KonvaJS stage. In ComponentDidMount, the value of this.stageRef.current is null. Any ideas why?

My code looks as follows:

import React, { useState } from "react"
import { Stage, Layer, Rect, Text } from 'react-konva';
import Konva from 'konva';

class MyComponent extends React.Component {

  constructor() {
    super()
    this.stageRef = React.createRef()
  }

  componentDidMount() {
    // this.stageRef.current is null here!
  }


  render() {
    return (
      <>
          <Stage id="canvas-text"
            width={400} height={163}
            className="stage"
            ref={this.stageRef}>
            <Layer>
              <Text fontFamily='Karla' fontSize={24} align='center' width={400} y={30} text={"Hello"} />
            </Layer>
          </Stage>
      </>
    )
  }
}

export default MyComponent;


Solution

  • The Stage component is a function component that forward the reference to its underlying child. You can inspect the sources:

    export const Stage = React.forwardRef((props, ref) => {
      return <StageWrap {...props} forwardedRef={ref} />;
    });
    

    A straight example as the one you provided shows that the ref references the underlying StageWrap component appropriately.