Skip to content

Instantly share code, notes, and snippets.

@MonteLogic
Created July 26, 2023 14:46
Show Gist options
  • Save MonteLogic/acf87a4652156ef6f7701e6ca51edd40 to your computer and use it in GitHub Desktop.
Save MonteLogic/acf87a4652156ef6f7701e6ca51edd40 to your computer and use it in GitHub Desktop.
import React, { useRef } from "react";
import ChildComponent, { ChildComponentRef } from "./ChildComponent";
const App: React.FC = () => {
// Create a reference to the child component
const childComponentRef = useRef<ChildComponentRef>(null);
// Function to trigger the child component's function
const triggerChildFunction = () => {
// Check if the child component reference is valid
if (childComponentRef.current) {
// Call the child component's function
childComponentRef.current.childFunction();
}
};
return (
<div>
{/* Button to trigger the child component's function */}
<button onClick={triggerChildFunction}>Trigger Child Function</button>
{/* Render the child component and pass the ref */}
<ChildComponent ref={childComponentRef} />
</div>
);
};
export default App;
import React, { forwardRef, useImperativeHandle } from "react";
interface ChildComponentProps {
// Define any props needed by the child component
}
export interface ChildComponentRef {
childFunction: () => void;
}
const ChildComponent: React.ForwardRefRenderFunction<
ChildComponentRef,
ChildComponentProps
> = (_, ref) => {
// Function to be triggered from the parent component
const childFunction = () => {
// Do something in the child component
console.log("Child function is triggered.");
};
// Expose the childFunction via ref to the parent component
useImperativeHandle(ref, () => ({
childFunction
}));
return (
// JSX for the child component
<div>{/* Child component content */}</div>
);
};
export default forwardRef(ChildComponent);
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
const rootElement = document.getElementById("root")!;
const root = ReactDOM.createRoot(rootElement);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment