I'm developing a React Native app with Hooks. (No Classes). When we use classes, we can create a ref to a child component like this.
<Child ref={component => this.childComponent = component} />
But, how to do this when we use Hooks?
I want something like this.
export default function Child() {
const foo = () => {
//do something
}
return(
//something
)
}
export default function Parent() {
const myFunc = () => {
ref.foo();
}
return(
<Child ref={.........} /> //This is what I want to know how to do?
)
}
I hope you understand what I'm trying to say.
In order to define refs with hooks, you need to use useRef
hook. And in order to apply ref to functional components you need to use forwardRef
and useImperativeHandle hook
function Child(props, ref) {
const foo = () => {
//do something
}
useImperativeHandle(ref, () => ({
foo
}));
return(
//something
)
}
export default React.forwardRef(Child)
export default function Parent() {
const childRef = useRef(null)
const myFunc = () => {
childRef.current.foo();
}
return(
<Child ref={childRef} />
)
}