Search code examples
javascripthtmlreactjselementref

How do I reference an element that is to be returned by a React component?


I want to start out by telling you that I am new to react and I come from a background of working almost entirely with vanilla JS and HTML. I want to know how to reference/pass an element as an argument in a function similar to how you would go about it in JS:

const myElement = document.getElementById("my-element");

or

const myElement = document.createElement("div");
function testFunc(element) {
return element.getBoundingClientRect();
}
testFunc(myElement);

I have googled a bit but haven't found any good answers, all I could find was about "ref" but I am sure there is a simpler solution.

This is what I have in React now:

import React from "react";
import "./myComp.css";

function myComp(props) {
  const sliderContainer = (
    <div className="slider-container" style={props.styles}></div>
  );

  function myFunc(element) {
      return element.getBoundingClientRect();
  }

  const elementDimensions = myFunc(sliderContainer);

  return { sliderContainer };
}

export default myComp;

But what i want to do is:

import React from "react";
import "./myComp.css";

function myComp(props) {
  const sliderContainer = "slider-container" //SOME SORT OF REFRENCE / SELECTOR, I'VE FIGURED OUT THAT querySelectors IS NOT THE RIGHT APPORACH

  function myFunc(element) {
      return element.getBoundingClientRect();
  }

  const elementDimensions = myFunc(sliderContainer);

  return (
    <div className="slider-container" style={props.styles}>
        <div className="myChild"></div>
    </div>
  );
}

export default myComp;

Solution

  • This should work:

    const sliderContainer = useRef(null);
    
    function myFunc(element) {
      return element.getBoundingClientRect();
    }
    
    useEffect(() => {
      const elementDimensions = myFunc(sliderContainer.current);
    });
    
    return (
      <div ref={sliderContainer} className="slider-container" style={props.styles}>
          <div className="myChild"></div>
      </div>
    );
    

    The ref property will assign the element to sliderContainer.current once the component has been mounted.

    Note that the value is initially set to be null: useRef(null).

    You must wait until the element is not null before accessing it as the element will not yet be mounted when the component is initially rendered.