'Emit data from stencil component to ReactJs component

How to catch emitted data in stencilJs component in ReactJs component?

I've created a CustomInputStencil component that has a prop of onChange that accepts a function. Inside the component I call the prop like this:

this.onChange(newData)

I'm expecting that whatever function I pass on the prop, it will receive the newData as a value. But it is not working:

<CustomInputFromStencil  onChange={(typedString) => console.log(typedString }/>

I want to get the value of the 'typedString' inside the stencil component but I am failing to do so.

Any tips/links that you can share?

I've been following this link:

https://stenciljs.com/docs/events

But I'm not sure how can I catch the emitted data/event in ReactJs without the use of @Listen.



Solution 1:[1]

Ideally you wouldn't pass a function as a prop to the stencil component, as HTML would only accept attributes as string, so your function might being translated as a string property, the same happen when we're passing object as prop to a stencil web-component.

Try the following approach using Stencil Events and see if it works

import { Component, Element, Event, EventEmitter, h } from '@stencil/core';

.
.
.
export class CustomInputStencil {

    @Event() changeInput: EventEmitter<string>


    render() {
        return (
            <Host>
                <input type="text" onInput={(event) => this.changeInput.emit(event.target.value)} />
            </Host>
        )
    }
}

And then listen to the changeInput event as the following

<CustomInputStencil onChangeInput={({ detail }) => console.log('detail', detail)} />

*Note: When you're creating Custom Events you name them to whatever you like, just ensure you're not naming as DOM native events (such as change, input, click, so on...)

*Note 2: As you saw, I've used the event in the React side as onChangeInput, that's how Stencil will translate your event name, with the prefix on followed by your event name in camel case.

Also, take a look into the following Stencil doc: Listening to events from a non-JSX element and in this great medium article Using Objects/Arrays as Props in Stencil Components

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Felipe Malara