React - How to get height of the particular div if you know its class

Viewed 64

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%')
  }
 }
2 Answers

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'));
Related