Attach methods to a function component in React

1. Create a ref with React.createRef.

const ref = React.createRef();

2. Pass the ref to the component.

import App from "./App"export default function AppContainer() {
const ref = React.useRef(null);
return (
<App ref={ref} />
)
}
import App from "./App"const container = document.createElement("div");
const props = {};
const element = React.createElement(App, { props, ref });
ReactDOM.render(element, container);

3. Attach methods to the ref.

function App(props, ref) {
ref.current = {
action: () => {
// do something
}
};
return (
<>
{/* Here render your components */}
</>
);
}
export default React.forwardRef(App);

4. Call methods from outside of the component.

ref.action()

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store