3

I am new to react. I need help with getting height of the coding div. Here is the react code that I am working with as an example:

 const buttonDiv = () => (
    <div
      className={styles.coding}
    >
      <button
        className={styles.codingButton}
        onClick={() => doSomething()}
      >
        Click Me
      </button>
    </div>
  );

So let say styles.coding class is coding and styles.codingButton is coding-button. Then there is another div with the class of let say coding2

How would I use the react to check and see what height for example was set on coding div. Really what I am trying to do is translate this jquery to react

function dosomething() {
  if($('.coding').height() > 0){
    $('.coding').height('0')
    $('.coding2').height('100%')
  }
  else {
    $('.coding').height('50%')
    $('.coding2').height('49%')
  }
 }
coder
  • 241
  • 5
  • 19
  • Have you seen this question yet: https://stackoverflow.com/questions/58942210/how-to-get-size-of-an-element-in-an-react-app-that-is-totally-based-on-functiona. Also I wouldn't use jquery with react: https://stackoverflow.com/questions/53507205/is-it-a-bad-practice-to-use-jquery-in-reactjs – justDan Jul 24 '21 at 03:02
  • I am not using jquery with react.. I am trying to use the logic of this jquery and rewrite it using react... overall I am just trying to get the height of the element. – coder Jul 24 '21 at 03:04
  • In jquery the DOM is the ultimate source of truth. This is not the case with react. In react we react based on state and props, not based on what is happening with some other piece of the DOM. So the question isn't does coding have a height, it's what causes coding's height to change? Once you know that you can work out the best way to notify coding2. – richbai90 Jul 24 '21 at 03:16

2 Answers2

0

In context to the comment that you're not using jQuery, I prefer you use window.getComputedStyle() method and pass the ref to the div as the argument. https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

avkat
  • 101
  • 1
  • 8
0

As mentioned above try to leverage ref to get what you want. Here's a little something that could maybe help you out. To see it work you can check it out here and use your console to check the logs. https://codepen.io/justdan/pen/zYwPWjp?editors=1010

const { useRef, useEffect } = React;

const ButtonDiv = () => {
  const div = useRef(null);
  
  function doSomething() {
    const height = div.current.offsetHeight;
    console.log('height', height);
    
    if (height > 0) {
      console.log('hit');
    };
  };
  
  return ( 
    <div
      ref={div}
      className={'coding'}
    >
      <button
        className={'codingButton'}
        onClick={() => doSomething()}
      >
        Click Me
      </button>
    </div>
  );
};
      
ReactDOM.render(<ButtonDiv />, document.getElementById('app'));
justDan
  • 2,302
  • 5
  • 20
  • 29