Skip to content
Advertisement

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

JavaScript

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

JavaScript

Advertisement

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:
JavaScript
  1. You can use EventEmitter (https://stenciljs.com/docs/events#events). In your button.tsx, you can add this:
JavaScript

Then add something like this on button’s onClick:

JavaScript

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

JavaScript
  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
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement