Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using Refs in Stencil

DZone 's Guide to

Using Refs in Stencil

A discussion of why refs are important for front-end code, followed by a quick tutorial on using ref attributes with the Stencil framework.

· Web Dev Zone ·
Free Resource

Why Use Refs?

The first question that you might ask yourself is why bother using element references? Let's clarify that.

In a typical data flow, you will pass props from the parent to it's child elements. When passing props, the child component will re-render and you will get it's new state. There are times that you will need to imperatively modify a child outside of this typical flow. Here are examples of things that might need different flow:

  • Triggering animation.
  • Usage of third-party components with their own API.
  • Implementation of forms where you might need to do things such as text selection or focus.

Now that we understand that we might need references to inner elements it's time to understand how to implement them in Stencil.

Stencil Refs

When you want to create a reference to an inner element in Stencil you will use the ref attribute. The ref attribute gets a function which accepts an element reference and returns void. In the function implementation, you will set the reference to a component member.

Let's see an example:

import {Component} from '@stencil/core';

@Component({
  tag: 'custom-text-input',
  shadow: true
})
export class CustomTextInput {
  private textInput?: HTMLInputElement;

  constructor() {
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    this.textInput.focus();
  }

  render() {
    return (
      <div>
        <input
          type="text"
          ref={el => this.textInput = el as HTMLInputElement} />

        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

In the example, you can see that the  CustomTextInput class has a private member called textInput. In the  render function, you set the reference to the input element using the following code:

ref={el => this.textInput = el as HTMLInputElement}

Then, when someone is clicking on the button, the focusTextInput is called and it will use the stored element to focus on the input element.

This is, of course, a simple example, but I hope that it helps you in setting a reference to an element.

Topics:
web dev ,front-end development ,javascript libraries ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}