Vijayashankar Aruchamy
Vijayashankar Aruchamy

Reputation: 131

Find the position of the React component in HTML

Elements are created and attached in the table, I want to find the position of a particular element, I have used UseRef hook,

const inputRef = useRef(null);

dynamic creation looks like

    return (
      <td style={{ margin: "1rem", padding: "1rem" }}>
        <Datetime
          ref={inputRef}
          closeOnSelect={true}
          dateFormat="MMM yy"
          timeFormat={false}
        />
      </td>
    );
  }

in UseEffect hook looks like

I tried both OffsetTop and getBoundingClientRect. both didnt help

    console.log(inputRef); //here no offsetTop is no there in current
    //console.log(inputRef.current.getBoundingClientRect());
  }, []);

outPut Looks as below in console.

{current: n}
current: n
props: Object
context: Object
refs: Object
updater: Object
_renderCalendar: ƒ () {}
_showView: ƒ () {}
viewToMethod: Object
nextView: Object
_updateDate: ƒ () {}
_viewNavigate: ƒ () {}
_setTime: ƒ () {}
_openCalendar: ƒ () {}
_closeCalendar: ƒ () {}
_handleClickOutside: ƒ () {}
_onInputFocus: ƒ () {}
_onInputChange: ƒ () {}
_onInputKeyDown: ƒ () {}
_onInputClick: ƒ () {}
state: Object
_reactInternals: FiberNode
_reactInternalInstance: Object
isReactComponent: Object
setState: ƒ () {}
forceUpdate: ƒ () {}
<constructor>: "n"

how to get the position of the current ref element

my code in the sandbox :

Edit React Template (forked)

Upvotes: 1

Views: 7877

Answers (2)

Anmol Bhardwaj
Anmol Bhardwaj

Reputation: 664

<html>
<head>
<style>
#test {
  top: 100px;
  margin: 10px;
  padding: 10px;
  width: 300px;
  position: relative;
  border: 5px solid black
}
</style>
</head>
<body>

<div>Just another Div </div> <!-- Remove this to see the value change !-->
<div>Just another Div </div> <!-- Remove this to see the value change !-->
<span>Just another Span </span> <!-- Remove this to see the value change !-->

<div id="test">
  <p>Click the button to get offsetTop for the test div.</p>
  <p><button onclick="myFunction()">Try it</button></p>
  <p>offsetTop is: <span id="demo"></span></p>
</div>

<script>
function myFunction() {
  var testDiv = document.getElementById("test");
  document.getElementById("demo").innerHTML = testDiv.offsetTop;
}
</script>

</body>
</html>

Try this: offsetTop works everytime.

Edit:

For a list, you can add an index/counter, to the ID of elements, and then it becomes easier to get ref from the DOM. Sandbox Link for React Demo

Upvotes: 2

Dhaval Parmar
Dhaval Parmar

Reputation: 27

You can get reference with id and then can apply getBoundingClientRect()

here is your code

import Datetime from "react-datetime";
import "./styles.css";
import "react-datetime/css/react-datetime.css";
import { useEffect, useRef } from "react";

export default function App() {
  let table = [];
  const inputRef = useRef(null);
  useEffect(() => {
    let a = document.getElementById('input');
    console.log("answer",a.getBoundingClientRect()); //here no offsetTop is no there in current
    //console.log(inputRef.current.getBoundingClientRect());
  });
  function getRow() {
    return (
      <td style={{ margin: "1rem", padding: "1rem" }}>
        <div id="input">
        <Datetime
          ref={inputRef}
          closeOnSelect={true}
          dateFormat="MMM yy"
          timeFormat={false}
        />
        </div>.
      </td>
    );
  }
  function getRows() {
    let row = [];
    for (let index = 0; index < 6; index++) {
      row.push(getRow());
    }
    return <tr>{row}</tr>;
  }

  function getTable() {
    for (let index = 0; index < 10; index++) {
      table.push(getRows());
    }
    return table;
  }

  return (
    <div className="App">
      <table style={{ border: "solid 1px blue" }}>
        <tbody>{getTable()}</tbody>
      </table>
    </div>
  );
}

Upvotes: -1

Related Questions