Search code examples
jsxrefstenciljs

StencilJS JSX use ref in as a Prop


I'm currently writing a StencilJS component with a ref to a element, which I need to pass as a @Prop to another element. Like so:

<canvas ref={el => this.canvas = el}></canvas>
<color-picker canvas={this.canvas}></color-picker>

When the color picker gets created, the this.canvas is still undefined, resulting in an error in color-picker.

How can I do this in JSX?


Solution

  • As already mentioned in the other answer, your reference only gets created after the first render, when an actual instance of your element becomes available that the reference can point to.

    The simplest way to solve this for you would be to mark the canvas member as state with the @State() decorator (which will trigger a re-render if its reference changes), and then conditionally render the <color-picker /> only once a valid reference is available:

    import { h, Component, Host, State } from '@stencil/core';
    
    @Component({ tag: 'my-component' })
    export class MyComponent {
      @State() canvas?: HTMLCanvasElement;
    
      render() {
        return (
          <Host>
            <canvas ref={el => this.canvas = el} />
            {this.canvas && <color-picker canvas={this.canvas} />}
          </Host>
        );
      }
    }