skip to Main Content

What is the best method to send data from a child component to the parent in Stencil.js?

I tried using a callback method, but it looks like it is imperative to use Events to accomplish this. It seems to me that we write a lot more to have 2 way data transfer than I would think it is necessary.
I have to mention that I am building a web components library that could be used later in either React or Angular projects.

2

Answers


  1. The recommended ways to communicate with a parent component is indeed through a custom event. But there are some other options as well, which might make more sense in some situations:

    Direct upward communication
    You can manually select a parent component and set attributes or properties on it:

    this.el.closest('my-parent').myProp = 123;
    

    Stencil Store
    A state library by the Stencil team to communicate with a central store, which other components can watch for changes. Note that I never tried it with Angular or React, but I think it should still work.

    Login or Signup to reply.
  2. If your are writing both parent and child components using JSX, standard data binding can work (if that’s what you mean by "send data"), as long as you bind objects not simple strings, numbers, or booleans.

    Suppose you have a parent component that renders a child component including a property of type object:

    export class Parent {
    
    anObject;
    
    render() {
        return(
            <child myObject={this.anObject}></child>
        );
    }
    

    Any changes that the child makes to its myObject will be reflected back to the parent’s anObject.

    If you are just using DOM, then, of course, this won’t work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search