Created
March 30, 2020 23:04
-
-
Save wagnerpaz/5a129be6d5985a15f3e3dc93ddff1ae6 to your computer and use it in GitHub Desktop.
How to expose a react component functions using forwardRef and useRefs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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