简体   繁体   中英

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.

我解决了设置延迟以调用 useEffect 钩子内的函数的问题:

setInterval(setHeightTweetsDiv, 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM