Skip to content

Instantly share code, notes, and snippets.

@wagnerpaz
Created March 30, 2020 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wagnerpaz/5a129be6d5985a15f3e3dc93ddff1ae6 to your computer and use it in GitHub Desktop.
Save wagnerpaz/5a129be6d5985a15f3e3dc93ddff1ae6 to your computer and use it in GitHub Desktop.
How to expose a react component functions using forwardRef and useRefs.
import React, { useRef } from 'react';
import Counter from './components/Counter';
export default () => {
const counterRef = useRef(null);
return (
<fieldset>
<legend>App.js</legend>
<Counter ref={counterRef} />
<button onClick={() => counterRef.current.addOne()}>Parent ref to Counter.addOne()</button>
</fieldset>
);
};
import React, { useState, forwardRef } from 'react';
export default forwardRef( (props, ref) => {
const [count, setCount] = useState(0);
const addOne = () => setCount(count + 1);
if(ref) ref.current = {addOne};
return (
<fieldset>
<legend>components/Counter.js</legend>
<div>Count: {count}</div>
<button onClick={addOne}>Add +1</button>
</fieldset>
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment