useRef hook for dynamic "onOutsideClick"?

I'm building a dashboard that will hold a bunch of items that can be individually edited if the user enters "Edit Mode" by clicking on an icon. While the user is in this mode, the app should give them a popup if they click outside of the item they're currently editing, so I started trying to implement something like this. But my issue here was that the items in the dashboard will be dynamically generated, from an array and a map function. So I want to dynamically assign refs to each of these items. I'm using only stateless functional components and styled-components.

I've tried to adapt Refs for dynamically generated components in React?'s solution to use with the new useRef hook. However, right now with my implementation ref.current for each item is undefined, plus I'm getting a Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? error in the console.

Working demo: https://codesandbox.io/s/dynamic-useref-clf1z

Edit: it would be different from the Outside Alerter codesandbox actually because the "outside area" would change based on what item is being edited, i.e. it would be everything on the dashboard outside of that item.

1 answer

  • answered 2019-07-18 15:40 Will Jenkins

    You're nearly there, you just have to use forwardRef in your child component as described in the docs:

    const Item = React.forwardRef((props, ref) => {
      return (
        <Container ref={ref} onClick={e => props.handleBoxClick(e, props.index)}>
          {props.itemId}
        </Container>
      );
    });
    
    export default Item;
    

    Updated sandbox here