I want to communicate from my Child component (a input form) to my parent component (popup) weather or not there is any data in the child.
The issue im facing is that the child component isn't a set child in the code it gets there with the {props.children} tag:
App.js structure:
<div>
<Popup>
</Child>
</Popup>
</div>
Popup.js structure:
<div>
{this.props.children}
</div>
Is there a way to do this without using a window.* variable or frankenstein-ing a stateSet/stateRead function in my App.js?
I have done some risky stuff here, but it gets the job done:
import React, { useEffect, useState } from "react";
export default function NewApp() {
return (
<Parent pProps="boss">
<Child text="Hello1" />
<Child text="Hello2" />
<Child text="Hello3" />
</Parent>
);
}
function Parent(props) {
const [children, setChildren] = useState([]);
function communicateWithMe(val) {
console.log("I am called", val);
}
useEffect(() => {
let _children = React.Children.map(props.children, (child) => {
console.log("Parent child", child);
return {
...child,
props: {
...child.props,
callBack: communicateWithMe
}
};
});
console.log("_children", _children);
setChildren(_children);
}, []);
return (
<div
style={{
background: "black",
color: "white"
}}
>
{children}
</div>
);
}
function Child(props) {
console.log(props);
return (
<div>
<p>{props.text}</p>
{props.callBack && (
<button
onClick={() => {
props.callBack("children baby");
}}
>
invoke Parent function
</button>
)}
</div>
);
}
here is the sandbox version to see it in action: https://codesandbox.io/s/sad-wood-5kuit3?file=/NewApp.js
Explaination:
What I aimed to do was to append the props on the children from the parent component. To do that, I casted the children (received in props by Parent) in to local state. Appended the prop to each child to have a callback function to communicate with the parent. The Parent component now returns the state variable that has the modified / appended props, instead of returns prop.children as it received!
EDIT:
As suggested, I have used React.Children to iterate over the children recieved by the parent in props.