Middle
If you throw a ref-reference to a class component, the ref value will be an instance of the class. Is it possible to do something similar with a functional component — pass a ref and get, for example, a function declared inside the component?
sobes.tech AI
Answer from AI
In React functional components, you cannot directly get an instance like in class components because functional components do not have an instance of a class. However, you can use forwardRef together with useImperativeHandle to pass a ref and define which methods or properties will be accessible from outside.
Example:
import React, { useImperativeHandle, forwardRef, useRef } from 'react';
const MyComponent = forwardRef((props, ref) => {
const localRef = useRef();
useImperativeHandle(ref, () => ({
myFunction: () => {
console.log('Calling function from parent');
}
}));
return <div ref={localRef}>Example component</div>;
});
// Usage:
// const ref = React.createRef();
// <MyComponent ref={ref} />
// ref.current.myFunction();
Thus, you can "expose" functions or data from a functional component via ref.