Skip to content

In stencil js, how can i check if button has been clicked in another component from a different class

I have a component called button.tsx, this components holds a function that does certain things when the button is clicked, this.saveSearch triggers the saveSearch() function.

button.tsx

  {((this.test1) || this.selectedExistingId) &&
                      (<button class="pdp-button primary"
                          onClick={this.saveSearch}>{this.langSave}</button>)
                    }

In sentence.tsx i want to be able to see when this button is clicked and show a certain div if the user has clicked it.

sentence.tsx

           {onClick={saveSearch} &&  (<div class="styles-before-arrow">{this.langConfirmSearchSaved}</div>)}

Answer

You have a few options:

  1. You can attach a click event listener for the button component in sentence.tsx. Take note that this may be trickier if you are working with elements which are encapsulated in Shadow DOM:
addButtonLister(): void {
  document.querySelector('.pdp-button')
          .addEventListener('click'), (e) => {
      // add your logic here.
  });
}
  1. You can use EventEmitter (https://stenciljs.com/docs/events#events). In your button.tsx, you can add this:
@Event({eventName: 'button-event'}) customEvent: EventEmitter;

Then add something like this on button’s onClick:

emitEvent() {
  customEvent.emit('clicked');
}

render () {
  return <button onClick={this.emitEvent}>{this.langSave}</button>
}

then from your sentence.tsx, add an event listener to your button component:

// say your button component's tag is <button-component>
document.querySelector('button-component')
        .addEventListener('button-event', (e) => {
    // your logic here.
});
  1. You can use Stencil Store, but depending on your overall use-case, I am not sure if this may be an overkill – https://stenciljs.com/docs/stencil-store#store-state