Itay Tur
Itay Tur

Reputation: 1737

React Material-UI Popper - popper ref doesn't work

I'm trying to achieve behaviour that when the popper is open and it's bottom exceeding the window bottom, it's placement will be change (from 'right' to 'right-end').

I think to get the bottom position from the ref, and see if it passed the bottom. problem is, what ever i try the ref.current is null.

these is what i tried so far:

  1. passing ref object to the Popper component props ref and popperRef. on useEffect current came out null.
  2. passing ref object to the div the popper wraps. same, on useEffect the current property came null.
  3. passing callback to the popper ref/popperRef-props, and to the div it wraps. the ref callback isn't invoked, when it mounts.

Popper component - example of passing callback to ref to the wrapped div

const customPopper = ({
 popperRef = (popperElement) => {}
}) => {
  const useStyles = makeStyles({
    Popper: { ...popperStyle, ['z-index']: '9999' }
  })
  const styles = useStyles();

  return (
    <Popper
      className={styles.Popper}
      placement={placement}
      open={open}
      anchorEl={anchorEl}
    >
      <ClickAwayListener onClickAway={handleClickAway}>

        <div ref={popperRef}>

          <CalendarPopover
            className={st(classes[calendarPopoverClass], { isMobile })}
            isShown
            withArrow={false}
            title={title}
            onClose={handleCloseClick}
          >
            {children}
          </CalendarPopover>
        </div>
      </ClickAwayListener>
    </Popper >
  )

Parent component ref handler

 const popperRefHandler = (popperRef: React.MutableRefObject<HTMLDivElement>) => {
    const popperBottom = popperRef.current.getBoundingClientRect().bottom;
    console.log('hello from popper mount in agenda cell, popper-bottom: ', popperBottom);

  }

EDIT 1 - Sandbox Example

https://codesandbox.io/s/material-ui-issue-forked-zy11e?file=/src/index.js

Upvotes: 3

Views: 8758

Answers (1)

Itay Tur
Itay Tur

Reputation: 1737

it works when passing callback. the argument it passes is DOM Element and doesn't have current property as in RefObject:

live example

big thx for Material UI team, for helping out: https://github.com/mui-org/material-ui/issues/23484

Upvotes: 1

Related Questions