<html>
<head>
<meta charset="UTF-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
const { useState, useEffect, useRef } = React;
function App() {
const myElementRef = useRef(null);
const [top, setTop] = useState('');
const [bottom, setBottom] = useState('');
const [left, setLeft] = useState('');
const [right, setRight] = useState('');
const [width, setWidth] = useState('');
const [height, setHeight] = useState('');
useEffect(() => {
const el = myElementRef.current;
const rect = el.getBoundingClientRect();
setTop(rect.top);
setBottom(rect.bottom);
setLeft(rect.left);
setRight(rect.right);
setWidth(rect.width);
setHeight(rect.height);
}, []);
return (
<div className="container">
<h3>React Js Get Element Position</h3>
<div ref={myElementRef}>This is my element</div>
<pre>Top: {top}</pre>
<pre>Right: {right}</pre>
<pre>Bottom: {bottom}</pre>
<pre>Left: {left}</pre>
<pre>Height: {height}</pre>
<pre>Width: {width}</pre>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
<style>
* {
box-sizing: border-box;
}
.container {
margin: 0 auto;
width: 600px;
text-align: center;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.12), 0 2px 4px 0 rgba(0, 0, 0, 0.24);
padding: 20px;
}
h3 {
margin-top: 0;
color: #333;
}
pre {
margin: 0;
color: #777;
}
pre:first-child {
margin-top: 10px;
}
pre:not(:last-child) {
margin-bottom: 10px;
}
</style>
</body>
</html>