D
D
Denis_13342021-02-02 23:33:03
React
Denis_1334, 2021-02-02 23:33:03

Getting the coordinates of an element in React?

Let's say we have a component:

import React, {useState} from 'react' 
let Block = () => {
     let [coors, setCoors] = useState(null) 
     return (
          <div>Hello World </div>
) 
}

I can add a click event to the div and it will return the event object in which I can get the getBoundingClientRect property.
But how can I get and store the coordinates of this element in coors during the function call without any events?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alex4answ, 2021-02-02
@Denis_1334

use ref and in componentDidMount()or useEffect()refer toref.current

const ref = useRef();

useEffect(() => {
  const rect = ref.current.getBoundingClientRect();
});

return <div ref={ref} />;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question