Using simple hacks you can pass data from child to parent.though it is very simple but it have a lot of use case. It mostly use for creating core component. Let's say you want to create select component where you want to pass Custom items during that time it is very helpful. There is lot of case you need it.
I have use simple hacked to pass data child to parent you may check my implementaitons below:
import React from "react";
// Define the type for the options
type Option = {
label: string;
value: string;
};
// Props for the ChildClass component
interface ChildClassProps {
// A function prop that takes an `Option` and returns a React node
customItems: (option: Option) => React.ReactNode;
}
const ParentClass: React.FC = () => {
return (
<ChildClass
customItems={(props: Option) => (
<div>
<div>{props.value}</div>
</div>
)}
/>
);
};
const ChildClass: React.FC<ChildClassProps> = ({ customItems }) => {
// Options array with objects that match the `Option` type
const options: Option[] = [
{ label: "green", value: "green" },
{ label: "blue", value: "blue" },
{ label: "red", value: "red" },
{ label: "yellow", value: "yellow" },
];
return (
<div>
<span>Child class</span>
{/* Iterate over the options and call `customItems` to render the custom content */}
{options.map((item, index) => (
<div key={index}>
{customItems(item)}
</div>
))}
</div>
);
};
export default ParentClass;
ParentClass Component:
The ParentClass component passes a customItems function as a prop to ChildClass. This function specifies how each option should be rendered.here you can pass your custom component.
ChildClass Component:
The ChildClass component iterates over the options array and calls the customItems function for each option. This allows ParentClass to define custom rendering for the options.
Top comments (0)