tim
tim

Reputation: 220

Components positions react dom

How do I use useRef to get the position of a component directly from the dom In this case I want to be able to get the position of the pageItem

import React, { useState } from 'react'
import PageItem from '../components/pageItem'
const LandingPage = () => {


    return (
        <div className={classes.mainContainer}
        >
            <PageItem/>
 
        </div>
    )
}

Upvotes: 0

Views: 56

Answers (2)

Ryu
Ryu

Reputation: 416

You can't add ref to custom elements like

 <PageItem/>

You can wrap custom elements with default elements like div or send refs through props to child default elements

Upvotes: 1

Dennis Vash
Dennis Vash

Reputation: 53884

If you have the ref you can use any element API like getBoundingClientRect

const LandingPage = () => {
  const divRef = useRef();

  useEffect(() => {
    console.log(divRef.current.getBoundingClientRect());
  }, []);
  return (
    <div ref={divRef} className={classes.mainContainer}>
      <PageItem />
    </div>
  );
};

Upvotes: 2

Related Questions