Search code examples
javascriptreactjsdropdownstyled-componentsreact-component

onBlur Not Working in React Dropdown Component


I have created the following React Dropdown Component:

const Dropdown = ({
  titleTag = 'button',
  titleCss,
  title,
  icon,
  menuCss,
  children,
  open,
  ...props
}) => {
  const [isOpen, setIsOpen] = React.useState(false)

  const handleClick = () => setIsOpen(state => !state)
  const handleBlur = () => setIsOpen(false)

  return (
    <DropdownBase>
      <Trigger
        as={titleTag}
        css={titleCss}
        onClick={handleClick}
        onBlur={handleBlur}
      >
        {title}
        {icon}
      </Trigger>
      <Submenu css={menuCss} open={isOpen}>
        {children}
      </Submenu>
    </DropdownBase>
  )
}

My problem is that the menu will not close if I click outside of the menu. I can open and close the menu by clicking on it. But I cannot close the menu by clicking away from the menu -- which is what I thought would happen with the handleBlur function. Indeed, that very function worked before I refactored the dropdown menu into a component.

So, what do I have to do so that the dropdown menu will close whenever I click outside of the dropdown menu?

Thanks.

Note: In case it is relevant, here are the relevant Styled Components that make up the Dropdown:


const DropdownBase = styled.div`
  display: inline-flex;
  position: relative;
  z-index: 10;
`

const Trigger = styled.div`
  cursor: pointer;
`

const Submenu = styled.div`
  display: ${props => (props.open ? 'block' : 'none')};

  position: absolute;
  top: 100%;
  left: 0;
  z-index: 20;

  ${Link} {
    display: inline-block;
    width: 100%;
  }
`

Solution

  • The div element can't receive focus event, you can add tabindex="0" to your Trigger component.

    can you see this