Categories
JavaScript Answers

How to get height of an element with React?

Spread the love

Sometimes, we want to get height of an element with React.

In this article, we’ll look at how to get height of an element with React.

How to get height of an element with React?

To get height of an element with React, we can use the useEffect hook.

For instance, we write

import React, { useState, useEffect, useRef } from "react";

export default () => {
  const [height, setHeight] = useState(0);
  const ref = useRef(null);

  useEffect(() => {
    setHeight(ref.current.clientHeight);
  });

  return <div ref={ref}>{height}</div>;
};

to define the height state with the useState hook.

And then we define a ref that we assign to the div.

Then we call useEffect with a callback to call setHeight with the height of the div.

We called it with no 2nd argument so the useEffect callback runs on every re-render to update the height.

Conclusion

To get height of an element with React, we can use the useEffect hook.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *