简体   繁体   中英

React - Menu dropdown dynamic absolute position

I am new to React and I am trying to translate my old website that was vanillaJS into ReactJS.

I have a button that should trigger a dropdown to open.

<button 
   type="button" 
   onClick={() => setMenuOpen(!isMenuOpen)} 
   ref={menuBtn}>menu</button>

and lower down in the DOM tree, I have:

{
isMenuOpen ?
  <nav style={{
     top: menuBtn.current.offset().top + menuBtn.current.outerHeight(),
     left: menuBtn.current.offset().left + (menuBtn.current.outerWidth() / 2)
  }}>
    ...
  </nav>
: null
            }

And

const [isMenuOpen, setMenuOpen] = useState(false)
let menuBtn = React.createRef()

at the start of my function Component .

But it does not work.

I get:

TypeError: Cannot read property 'offset' of null

Also, I think that even if this was working, it would not be responsive. If the user click on the button, then resize the window, it will not follow where the button is.

Thank you !

The answer was the use .current.getBoundingClientRect() instead of .current.offset()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM