DEV Community

Borislava Kirova
Borislava Kirova

Posted on

Attach methods to a function component in React

1. Create a ref with React.createRef.

const ref = React.createRef();
Enter fullscreen mode Exit fullscreen mode

2. Pass the ref to the component.

You can either pass the ref to the component in a render function.

import App from './App'

export default function AppContainer() {
const ref = React.useRef(null);

  return ( 
    <App ref={ref} />
  )
}
Enter fullscreen mode Exit fullscreen mode

Or create and render the component via the react API and pass the ref as a parameter to React.createElement function.

import App from './App'

const container = document.createElement("div");
const props = {};
const element = React.createElement(App, { props, ref });
ReactDOM.render(element, container);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

4. Call methods from outside of the component.

ref.action()
Enter fullscreen mode Exit fullscreen mode

Discussion (0)