Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StencilJS JSX use ref in as a Prop

Tags:

jsx

ref

stenciljs

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?

like image 385
Elger van Boxtel Avatar asked Nov 15 '25 09:11

Elger van Boxtel


1 Answers

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>
    );
  }
}
like image 150
Simon Hänisch Avatar answered Nov 18 '25 19:11

Simon Hänisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!