Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-like refs in lit-html / lit-element?

Does lit-html have by any change something like React's ref feature? For example in the following pseudo-code inputRef would be a callback function or an object { current: ... } where lit-html could pass/set the HTMLElement instance of the input element when the input element is created/attached.

// that #ref pseudo-attribute is fictional
html`<div><input #ref={inputRef}/></div>`

Thanks.

like image 426
Natasha Avatar asked Nov 26 '19 02:11

Natasha


3 Answers

In lit-element you can use @query property decorator. It's just syntactic sugar around this.renderRoot.querySelector().

import { LitElement, html, query } from 'lit-element';

class MyElement extends LitElement {
  @query('#first')
  first;

  render() {
    return html`
      <div id="first"></div>
      <div id="second"></div>
    `;
  }
}
like image 173
lispmachine Avatar answered Nov 05 '22 03:11

lispmachine


lit-html renders directly to the dom so you don't really need refs like you do in react, you can use querySelector to get a reference to the rendered input

Here's some sample code if you were only using lit-html

<html>

<head>
  <title>lit-html example</title>
  <script type="module">
    import { render, html } from 'https://cdn.pika.dev/lit-html/^1.1.2'; 
    const app = document.querySelector('.app'); 
    const inputTemplate = label => { 
      return html `<label>${label}<input value="rendered input content"></label>`;
    }; 
    // rendering the template
    render(inputTemplate('Some Label'), app);
    // after the render we can access it normally
    console.log(app.querySelector('input').value);
  </script>
</head>

<body>
  <div class="app"></div>
  <label>
    Other random input
    <input value="this is not the value">
  </label>
</body>

</html>

If you're using LitElement you could access to the inner elements using this.shadowRoot.querySelector if you're using shadow dom or this.querySelector if you aren't

like image 4
Alan Dávalos Avatar answered Nov 05 '22 02:11

Alan Dávalos


As @WeiChing has mentioned somewhere above, since Lit version 2.0 you can use the newly added directive ref for that: https://lit.dev/docs/templates/directives/#ref

like image 4
Natasha Avatar answered Nov 05 '22 03:11

Natasha