OnBlur closing react component if clicked inside

Viewed 713

I have created a React component using Material UI as below

<Popper
  open={open}
  anchorEl={anchorRef.current}
  onBlur={handleToggle}
  transition
  disablePortal
>
  <MenuList autoFocusItem={open}>
    <MenuItem>Tom</MenuItem>
    <MenuItem>Patt</MenuItem>
  </MenuList>
  <input type="text" name="Student" onChange={getStudent}></input>
</Popper>

In the above component i have MenuList and TextField. I tried to add onBlur={handleToggle} thinking that, it will close the component if clicked outside of it but its closing even when i am trying to add text in TextField using onChange={getStudent}, Why is it happening and how to close Component only if clicked outside of it? Thanks.

1 Answers

You can use ClickAwayListener component to detect whether the user is clicking outside of the Popover area.

<ClickAwayListener onClickAway={() => setOpen(false)}>
  <span>
    <Popper
      open={open}
      anchorEl={ref.current}
      transition
      disablePortal
    >
      <MenuList autoFocusItem={open}>
        <MenuItem>Tom</MenuItem>
        <MenuItem>Patt</MenuItem>
      </MenuList>
      <input
        type="text"
        name="Student"
      />
    </Popper>
    <Button variant="outlined" onClick={() => setOpen((o) => !o)} ref={ref}>
      Nothing
    </Button>
  </span>
</ClickAwayListener>

Live Demo

Edit 63953850/onblur-closing-react-component-if-clicked-inside/63954643#63954643

Related