'How do i pass data up from a child web component to it's direct parent element
I need to basically pass a value down to my web component, I will then do some random thing to it, now I want to pass that new value back up to my React Comnponent. How do I do that?
function MyReactcomp() {
const [state, setState] = useState("Justin is cool");
return (
<div className="Wrapper">
<customweb-component state={state} />
</div>
);
}
Now inside the customweb-component, I will change state to "No your not!!". How can I pass this value back up from my web component to my Rea t Copmponent? I know I can pass a function down because you can only pass strings down
Solution 1:[1]
In react, the transfer of data is 1-way only, i.e., from Parent-to-Child
However, if you need to have a handler in the parent element for some data change in the child element, you can use Lifting Up State
This could help achieving what you need.
If not, please provide more details about the actual case scenario
Solution 2:[2]
I figured out that you need to attach a custom event handler to an element in your Lit-html template. You can then use getElementById or something to that effect and listen for the event in the parent component.
This is a combination of my answer and Harshal Patil's he took into account that using Reacts built-in features for manipulating the DOM is preferable to manipulating it directly.
import React, { useEffect, useRef } from 'react';
function MyReactcomp() {
const [state, setState] = useState("Justin is cool");
const webCompRef = useRef();
useEffect(() => {
webCompRef.addEventListener('tab-select', (event) => {
setState("No he is not!!")
})
}, []}
return (
<div className="Wrapper">
<customweb-component ref={webCompRef} state={state} />
</div>
);
}
This pattern will allow you to pass your data down through the web components attributes. You can then listen for your native or custom events. This is cool because now components can cross frameworks and libraries, if one team is using React and the other is using Angular they can share components and keep there UI in sync.
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 | BHAVYA BHUSHAN |
| Solution 2 |
