Skip to content
Advertisement

ReactJS/CSS: How to set div height based on other element height?

I’m trying to set an fixed height to a div, to force the overflow scroll. The problem is, I’m doing this with JavaScript, inside a useEffect hook, but it’s not working well. Sometimes the height it’s set well, but at the most times is wrong.

I created a function inside the component, then, call it inside a useEffect hook:

const TweetsPanel: React.FC<TweetsPanelType> = ({ tweetsData }) => {

  function setHeightTweetsDiv() {
    const height = document.getElementById('last-boicotes')?.clientHeight;
    // the "last-boicotes" div it's in another component, in the same page.
    document.getElementById('tweets-content').style.height = `${height}px`;
  }

  useEffect(() => {
    setHeightTweetsDiv();
  }, []);

  return (
    <>
      <div>
        <h2>Tweets</h2>
      </div>

      <div id="tweets-content">
        // tweets
      </div>
    </>
);

Seems to work, but its setting the wrong height. After reload the page some times, it works:

DevTools inspect

Rendered code

I’m trying to fix the height to set a equal height. The left column will always be fully displayed, the right one, will always be bigger, so i need this one to be height fixed, the same height of the left, and the overflowed content will be scrollable.

I can’t use flex-box, cause inside each column has an div to the heading and another to the content. And the div that I need to scroll it’s inside the main column div.

HTML structure

If someone knows how to achieve this in some other way, please tell me.

Sorry for my English and thanks in advance.

Advertisement

Answer

I solved the problem setting a delay to call the function inside the useEffect hook:

setInterval(setHeightTweetsDiv, 1000);
Advertisement