Reputation: 3419
I have 3 components, one parent component which renders 2 child components. I need to access the function of the 1st child component from the 2nd child component.
Sample Code:
Parent Component:
class Main extends React.Component {
myRef: React.RefObject<any>;
constructor(props: any) {
super(props);
this.myRef = React.createRef();
}
return (
<div>
{/* some code */}
<ChildOne />
<ChildTwo />
</div>
);
ChildOne:
function ChildOne() {
const childOneFunction = () => {
console.log("Hello from child one");
};
return <div>{/* some code */}</div>;
}
}
ChildTwo:
function ChildTwo() {
useEffect(() => {
childOneFunction();
});
return <div>{/* some code */}</div>;
}
I need call the childOneFunction()
from childTwo component. Is it possible without any 3rd party library like redux?
Upvotes: 0
Views: 232
Reputation: 28684
Maybe you can try with forwarding refs and useImperativeHandle.
Demo:
let ChildOne = React.forwardRef((props, ref) => {
React.useImperativeHandle(ref, () => ({
childOneFunction: () => {
console.log('Hello from child one');
},
}));
return <div>1</div>;
});
let ChildTwo = React.forwardRef((props, ref) => {
return (
<div
onClick={() => {
ref.current.childOneFunction();
}}
>
2
</div>
);
});
export default function App() {
const test = React.useRef();
return (
<div>
<ChildOne ref={test} />
<ChildTwo ref={test} />
</div>
);
}
Upvotes: 2