Home > Software engineering >  How can I "getElementById" height of div and show button when height is >= 500
How can I "getElementById" height of div and show button when height is >= 500

Time:10-25

I'm trying to get the height of a div and show a "scroll back to top" button when a certain amount of pixels are passed. But I can only seem to get height of said div and either only show or hide the button. Currently it says the height is 480. Here is my code:

const [topButton, setTopButton] = useState(false)

const vendorCard = document.getElementById('vendorCard')?.offsetHeight!

  useEffect(() => {
  if(vendorCard > 480){
    setTopButton(true)
  } else {
    setTopButton(false)
  }      
  }, [])

  // Need to hide button until scrolled
  const scrollToTop = () => {
    document.getElementById('vendorCard')?.scrollTo({
      top: 0,
      behavior: 'smooth'
    })!
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js">

{topButton && <div>
          <button
            onClick={scrollToTop}
            className="hidden"
            id="resetScroll"
            style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
              padding: '10px',
              border: 'none !important'
            }}
            type="button"
          >
            <ArrowUpwardIcon />
            <p style={{ fontSize: '0.7em', fontWeight: '200' }}>BACK</p>
          </button>
        </div>}
</script>

CodePudding user response:

If I am understanding correctly, you are using useEffect and telling it to only check that if statement once at load by giving it an empty array as a second argument.

You need an onScroll listener on vendorcard. Im not sure what vendorcard is as its not in your code.

assuming this is vendor card...

<div id='vendorcard' onScroll = {handleScroll}></div> 

then you want to make a function...

function handleScroll(event){console.log(event.currentTarget)}
// event.currentTarget exposes the properties you need to access to build your if statement that alters your state.

You shouldnt need useEffect at all in that function as it doesnt really have a dependancy. You basically call that function onScroll, then inside that function you write your if statements to set the state of topButton. However, it is possible, depending on your end goal and code setup, that useEffect may be needed somewhere.

You could also write the function anonymously for onScroll if it is short. However, its almost always better for readability if you use a seperate function.

Also, avoid interacting with the DOM directly. QuerySelector,getElementById etc.... should only be used in very rare circumstances inside of React. There is almost always another way.

  • Related