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
x
5
1
{((this.test1) || this.selectedExistingId) &&
2
(<button class="pdp-button primary"
3
onClick={this.saveSearch}>{this.langSave}</button>)
4
}
5
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
1
2
1
{onClick={saveSearch} && (<div class="styles-before-arrow">{this.langConfirmSearchSaved}</div>)}
2
Advertisement
Answer
You have a few options:
- 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
7
1
addButtonLister(): void {
2
document.querySelector('.pdp-button')
3
.addEventListener('click'), (e) => {
4
// add your logic here.
5
});
6
}
7
- You can use
EventEmitter
(https://stenciljs.com/docs/events#events). In yourbutton.tsx
, you can add this:
JavaScript
1
2
1
@Event({eventName: 'button-event'}) customEvent: EventEmitter;
2
Then add something like this on button’s onClick
:
JavaScript
1
8
1
emitEvent() {
2
customEvent.emit('clicked');
3
}
4
5
render () {
6
return <button onClick={this.emitEvent}>{this.langSave}</button>
7
}
8
then from your sentence.tsx, add an event listener to your button component:
JavaScript
1
6
1
// say your button component's tag is <button-component>
2
document.querySelector('button-component')
3
.addEventListener('button-event', (e) => {
4
// your logic here.
5
});
6
- 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