Replies: 1 comment
-
|
In Preact, a
const myRef = useRef();
// myRef.current = Preact component instance
// myRef.current.base = actual DOM element
console.log(myRef.current.base.clientHeight); // works
console.log(myRef.current.base.offsetHeight); // also worksBut Correct solution: import { forwardRef } from 'preact/compat';
const MyComponent = forwardRef(function MyComponent(props, ref) {
return <div ref={ref} className="my-component">{props.children}</div>;
});
// Parent:
const domRef = useRef();
<MyComponent ref={domRef} />
// domRef.current = the <div> DOM element directly
// domRef.current.clientHeight works perfectlyThis is the correct, stable, React-compatible pattern. On your two options:
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I recently ran into a situation where I converted a DOM element into a component, but kept the
refon it. Suddenly, the parts of my code that used theclientHeightof myrefno longer worked because apparently components only supportoffsetHeight. I now have two options:forwardRefto pass the reference to the DOM element from my component to the parent. This looks ugly.clientHeightwithoffsetHeight, but that might miscalculate when it gets a border or pseudo-elements.Is there a better way to get the client height of a component?
Beta Was this translation helpful? Give feedback.
All reactions