There are three options, I don't know which one is the best.
//@ts-nocheck
import React, { useEffect, useRef } from "react";
export const Child = React.forwardRef((props, ref) => {
console.log("ref: ", ref);
// option 1
// const divRef = ref || React.createRef();
// option 2, it's same with option 3?
// const _ref = useRef(null);
// const divRef = ref || _ref;
// option 3, one line
const divRef = useRef(ref?.current);
useEffect(() => {
console.log("divRef: ", divRef.current);
}, []);
return <div ref={divRef}>child</div>;
});
Use Child
component inside Parent
component:
const Parent = () => (
<div>
<Child />
</div>
);
render(<Parent />);
As you can see, the Parent
component didn't create and pass ref to Child
. The logic is if the Parent
passed ref, use it, if not, create one in the Child
component
When I run it and check the console log, all of them seem correct because I can get the divRef
.
divRef: <ref *1> HTMLDivElement {...}