1

I know findDOMNode is a no-no, I have a feeling that I can get rid of it.

I recently refactored my component to use a Button component instead of a button tag. It looks like this now:

<Button
   ref={(input) => this.toggleZipLink = input}>
   Add New Zip
</Button>

and I have a function in my component that gets called from another component via a prop:

shouldClickOutside(e) {
    if (findDOMNode(this.toggleZipLink).contains(e.target)) {
        return false;
    }
    return true;
}

I have to use findDOMNode because this.toggleZipLink is a component. If Button was a button I wouldn't need it.

Is there any way I can expose the inner button tag to it's parent? I notice that this.toggleZipLink has a refs object, but it seems to be empty. For reference, Button is not stateless function component, so it should support ref's.

Solution Edit:

Inside Button I added a ref ref={(button) => this.button = button}. Then in the parent div I can access it as via this.toggleZipLink.button.

Dave
  • 1,645
  • 2
  • 23
  • 39
  • 1
    Does this answer your question? [React DnD: Avoid using findDOMNode](https://stackoverflow.com/questions/40499267/react-dnd-avoid-using-finddomnode) – Zach Aug 14 '20 at 19:58

1 Answers1

1

You could expose some other non-ref prop on Button (named, say, buttonRef) to pass your ref callback through on. Button's render then passes this.props.buttonRef as ref to the underlying button.

class Button extends Component {
  render() {
    const { buttonRef, ...passThroughProps } = this.props;
    return <button {...passThroughProps} ref={buttonRef} />
  }
}

Also, you could just take the ref onto Button and then access it via toggleZipLink.whateverYouNamedYourRef.

Passing through refs is hard and takes some boilerplate.

Alex Guerra
  • 2,556
  • 3
  • 18
  • 24