React useCallback/useState - Transforming (scale) an element based on screen width

Viewed 27

I have a function which fires on scroll - it transforms the element by setting a variable which I apply to said element. Currently it works well, but isn't very flexible in terms of screen-sizes.

 const handleScroll = useCallback(
    (event) => {
      requestAnimationFrame(() => {
        const box = ref.current.getBoundingClientRect()
        let percentScrolled = 1.25 - box.top / window.scrollY
        let scale = percentScrolled * 1.05
        if(window.innerWidth > 1600) {
          setScale(Math.max(1, Math.min(scale, 1.29)))
          ref.current.style.marginBottom = '5em';
        } else {
          setScale(Math.max(1, Math.min(scale, 1.14)))
          ref.current.style.marginBottom = '2em';
        }
      })
    },
    [setScale],
  )

At the moment I have to use Math.max() in order to prevent it growing larger than the screen (I wan't it to scale from small, up to full width, currently i've had to set the max by screen size) I've tried modifying it to use the ref.current.getBoundingClientRect().width in combination of window.innerWidth but now it doesn't get smaller as you scroll back up.

I'm not sure what i'm missing, or if there is a better way to handle it. Any help would be greatly appreciated

  const handleScroll = useCallback(
    (event) => {
      requestAnimationFrame(() => {
        const box = ref.current.getBoundingClientRect()
        const boxWidth = ref.current.getBoundingClientRect().width;
        console.log(boxWidth)

        let percentScrolled = 1.25 - box.top / window.scrollY
        let scale = percentScrolled * 1.05

        if(window.innerWidth > 1600) {
          if(boxWidth >= window.innerWidth) {
            setScale(Math.max(1, Math.min(scale, 1.29)))
          } else {
            setScale(Math.max(1, Math.min(scale, 5)))
          }
          ref.current.style.marginBottom = '5em';
        } else {
          setScale(Math.max(1, Math.min(scale, 1.14)))
          ref.current.style.marginBottom = '2em';
        }
      })
    },
    [setScale],
  )
0 Answers
Related