Home > Blockchain >  Passed ref to child is null
Passed ref to child is null

Time:10-04

I have MUI Drawer component in which I render another component called NotificationsMenu. The NotificationsMenu is a MUI Popover component.

I want to anchor the Popover to the Drawer component so the Popover will be positioned relative to the Drawer which can be open (240px width) or closed (66px width).

I think I should use a ref for this. If I have the reference to the Drawer (parent component) I can just use that to set the Anchor for the Popover:

// NotificationsMenu.tsx

const NotificationsMenu = (props, ref) => {
  console.log(props, ref);
  const [anchorEl, setAnchorEl] = useState(null);

  const handleClick = (event) => {
    setAnchorEl(ref.current);
  };

  return (
    <>
      <ListItem disablePadding>
      ...
      </ListItem>

      <Popover
        anchorEl={anchorEl}
        ...
       > Content
      <Popover/>
    </>
}
// DrawerContainer.tsx

import React, {useRef} from 'react';

export const DrawerContainer = () => {
  const elRef = useRef(null);

  return (
    <Drawer variant="permanent" open={open}>
      <List>
        <NotificationsMenu ref={elRef}/>
      </List>
    </Drawer>
  );
}

This isn't working because ref.current in the Notifications.menu is null. Using react": "^17.0.2",

CodePudding user response:

You just need to destructuring the ref on notificationmenu components like this:

const NotificationsMenu = ({ ref }) => {
  console.log(ref);
  const [anchorEl, setAnchorEl] = useState(null);

  const handleClick = (event) => {
    setAnchorEl(ref.current);
  };

  return (
    <>
      <ListItem disablePadding>
      ...
      </ListItem>

      <Popover
        anchorEl={anchorEl}
        ...
       > Content
      <Popover/>
    </>
}

CodePudding user response:

Resolved the issue. Just to clarify, the child component NotificationsMenu had an forwardRef assigned:

export default forwardRef(NotificationsMenu);

This allows the usage of ref in functional components.

The issue was that I needed to pass the Ref also on the Drawer component:

<Drawer variant="permanent" open={open} ref={elRef}>
  • Related