For class component we can use
this._reactInternalFiber._debugOwner.type.name
as mentioned in React Access parent component name.
But is there any way to do same in function component?
For class component we can use
this._reactInternalFiber._debugOwner.type.name
as mentioned in React Access parent component name.
But is there any way to do same in function component?
Based on this answer you can make a custom hook to display the parent's name:
import { useEffect, useRef, useState } from "react";
function FindReact(dom, traverseUp = 0) {
const key = Object.keys(dom).find((key) => {
return (
key.startsWith("__reactFiber$") || // react 17+
key.startsWith("__reactInternalInstance$")
); // react <17
});
const domFiber = dom[key];
if (domFiber == null) return null;
// react <16
if (domFiber._currentElement) {
let compFiber = domFiber._currentElement._owner;
for (let i = 0; i < traverseUp; i++) {
compFiber = compFiber._currentElement._owner;
}
return compFiber._instance;
}
// react 16+
const GetCompFiber = (fiber) => {
//return fiber._debugOwner; // this also works, but is __DEV__ only
let parentFiber = fiber.return;
while (typeof parentFiber.type == "string") {
parentFiber = parentFiber.return;
}
return parentFiber;
};
let compFiber = GetCompFiber(domFiber);
for (let i = 0; i < traverseUp; i++) {
compFiber = GetCompFiber(compFiber);
}
return compFiber;
}
const useParentName = () => {
const ref = useRef();
const [parentName, setParentName] = useState();
useEffect(() => {
if (ref.current) {
let node = FindReact(ref.current, 1);
setParentName(node.type.name);
}
}, []);
return { ref, parentName };
};
const Child = () => {
const { ref, parentName } = useParentName();
return (
<div ref={ref}>
<div>{parentName}</div>
</div>
);
};
export default function App() {
return (
<div className="App">
<Child />
</div>
);
}
But you will need to use ref
inside the child component to display the parent's name