Reputation: 45
Has anyone managed to find a way for using custom events created in StencilJS in ReactJS using React useRef() and useEffect() hooks?
I have looked at the StencilJS documentation for this they only cover this for arrays and custom objects.
I am new to front-end development, so any help would be a step in the right direction.
Thanks in advance.
Upvotes: 2
Views: 1529
Reputation: 45
I have managed to solve this issue for my functional component using the useRef() and useEffect() React hooks, with guidance from this article, as seen below:
import React, { useState, useRef, useEffect } from "react";
const Form = () => {
const [ name, setName ] = useState('');
const nameInputField = useRef(null);
useEffect(() => {
const { current } = nameInputField;
//First parameter is the name of the event in Stencil component
//Second parameter is the custom function
current.addEventListener('onChanged', () => setName('Steph'););
//Component is unmounting so removing the event listener
return () => current.removeEventListener('onChanged', () => setName('Steph'););
}, []);
return (
<stencil-component-with-event
ref={nameInputField}
value={name}
type='text'
/>
)
}
I hope this makes sense:)
Upvotes: 2