I want to get a elements offsetTop. But it will be undefined.
How can I get it? I checked mdn.https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop
But I couldn't find how to do it.
import "./styles.css";
export default function App() {
const dividers = document.getElementsByClassName("divider");
const offsets = [
dividers[0]?.offsetTop,
dividers[1]?.offsetTop,
dividers[2]?.offsetTop,
dividers[3]?.offsetTop
];
console.log("dividers", dividers);
console.log("offsets", offsets);
return (
<>
<p style={{ height: 200 }}>aaaaaaaaa</p>
<div className="divider">
_______________________________________________
</div>
<p style={{ height: 200 }}>bbbbbbbbb</p>
<div className="divider">
_______________________________________________
</div>
<p style={{ height: 200 }}>cccccccccccc</p>
<div className="divider">
_______________________________________________
</div>
<p style={{ height: 200 }}>ddddddddd</p>
<div className="divider">
_______________________________________________
</div>
</>
);
}
Here is the Codesandbox.
CodePudding user response:
try this
import { useLayoutEffect, useRef, useState } from "react";
import "./styles.css";
export default function App() {
const [offsets, setOffsets] = useState();
const ref = useRef();
useLayoutEffect(() => {
const dividers = document.getElementsByClassName("divider");
setOffsets(dividers);
}, []);
console.log(offsets);
return (
<>
{offsets && (
<>
<p style={{ height: 200 }}>aaaaaaaaa</p>
{offsets[0]}
<div ref={ref} className="divider">
_______________________________________________
</div>
<p style={{ height: 200 }}>bbbbbbbbb</p>
<div ref={ref} className="divider">
_______________________________________________
</div>
<p style={{ height: 200 }}>cccccccccccc</p>
<div ref={ref} className="divider">
_______________________________________________
</div>
<p style={{ height: 200 }}>ddddddddd</p>
<div ref={ref} className="divider">
_______________________________________________
</div>
</>
)}
</>
);
}
CodePudding user response:
I've used Array and fill to make it less repetitive and to be able to set the ref's indexes dynamically instead of hardcoding. Code sandbox