Why is my useRef not working on my overflowing absolute div with Styled Components?

Trying to create a dropdown with Styled Components that if the dropdown is going past the viewport a right will be applied, example:

Component (stripped):

export default function SoTest() {
    const [dropActive, setDropActive] = useState(false)
    const ref = useRef()
  
    return (
      <>
      <Foo
        onMouseEnter={() => setDropActive(true)}
        onMouseLeave={() => setDropActive(false)}
      >
        // Removed code
      </Foo>
        <DropContainer
          ref={ref}
          isOverflow={useIsOverflow(ref)}
          dropdownActive={dropdownActive}
          onMouseEnter={() => setDropActive(true)}
          onMouseLeave={() => setDropActive(false)}
        >
          // Removed code
        </DropContainer>
      </>
    )
  }

then in the style, I'm attempting:

const DropContainer = styled.div`
  display: ${({ dropdownActive }) => (dropdownActive ? 'flex' : 'none')};
  right: ${({ isOverflow }) => (isOverflow ? '18px' : '')};
  position: absolute;
  z-index: 10;
`

my hook useIsOverflow I have:

import { useState, useLayoutEffect } from 'react'

export default function useIsOverflow(ref) {
  const [isOverflow, setIsOverflow] = useState(undefined)

  useLayoutEffect(() => {
    const { current } = ref
    const { clientWidth, scrollWidth } = current

    const trigger = () => {
      const hasOverflow = scrollWidth > clientWidth ? true : false
      setIsOverflow(hasOverflow)
    }

    if (current) trigger()
  }, [ref])

  return isOverflow
}

When I log ref I get:

offsetHeight: 0
offsetLeft: 0
offsetParent: null
offsetTop: 0
offsetWidth: 0

but I'm not getting back a boolean of true when I move the dropdown to the right and click Foo. What am I doing wrong and why am I not able to detect the ref or what can I do to detect if the dropdown is going past the viewport to apply right?



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations