Skip to content

Instantly share code, notes, and snippets.

@jeremybarbet
Last active April 18, 2020 20:48
Show Gist options
  • Select an option

  • Save jeremybarbet/fa161dccf5cec7a2f79b893db1c98758 to your computer and use it in GitHub Desktop.

Select an option

Save jeremybarbet/fa161dccf5cec7a2f79b893db1c98758 to your computer and use it in GitHub Desktop.
Because I always forget about it and spend hours looking for this solution on Google
import React, { forwardRef, useImperativeHandle, useRef } from 'react';
const Component = forwardRef((_, ref) => {
useImperativeHandle(ref, () => ({
internalPress() {
// whatever you want to call
},
}));
return <div />; // DOM
});
const App = () => {
const componentRef = useRef(null);
const handlePress = () => {
componentRef.current?.internalPress();
};
return (
<Component ref={componentRef} />
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment