Skip to content

Key prop

Kiran Mantha edited this page Oct 17, 2024 · 3 revisions

The latest PlumeJS version (^4.1.8) introduced one important feature key attribute. Just like react, when the framework detects any change in key value on a Component, then it will straight away replace the current component version with newer version. This is very similar to that of resetting a component entirely based on key. That means when the existing version is replaced, this feature will execute unmount lifecycle hook on existing version and beforeMount, mount lifecyclehooks on newer version.

Similarly, we can use keyed nodes in Component html. This ensure that the eventlisteners don't hold stale data. Best example is rendering html in loop. When a fresh piece of loop arrive, the html should update all the listeners. This can be achived by using key attribute on those nodes.

Example:

@Component({
  selector: 'app-key-sample'
})
class SampleComponent {
  data = [1,2,3,4];

  render() {
    return html`
      ${this.data.map((v) => {
        return html`<div key=${v}>
         ${v}
        </div>`
      })}
    `
  }
}

Clone this wiki locally