1

I know I can access a ref for the child like so

ParentComponent extends React.Component {

  constructor() {
    this.myRef = React.createRef();
  }


  render() {
    return (
    <ChildComponent>
      <div ref={myRef}>Blah</div>
    <ChildComponent>
    );
  }
}

ChildComponent extends React.Component {

  render() {
    const {children} = this.props.children;
    console.log(children.ref) // Will get DOM element
    return {children}
  }
}

But is there a way to get the DOM element without passing in the ref from the parent component so that my child component can get the ref from this.props.children?

At a high level i'm trying to make an extensible component ChildComponent so that every parent component that uses ChildComponent doesn't have to declare refs for the child component.

Evan
  • 222
  • 3
  • 9
  • This smells like you're doing something in a non-React way. Can you expand more on what this extensible component should do? – AKX Oct 17 '18 at 19:03
  • Sure. I have a tooltip component that I want to display on a text label and I want it to display only when text overflows the div it's contained in. My current solution is to check overflows is inspired from https://stackoverflow.com/questions/42012130/how-to-detect-overflow-of-react-component-without-reactdom – Evan Oct 17 '18 at 19:12
  • Sounds like you could use a render prop: `}>{text}` and have the overflow check logic in this component (it can use a `
    ` to wrap `this.props.children`, for instance), and then have it render the `tooltip` prop when required.
    – AKX Oct 17 '18 at 19:23
  • Im not quite familiar with render props, but from your example would that mean that I would have to wrap every tooltip with ? Seems like it could get messy – Evan Oct 17 '18 at 19:42

1 Answers1

0

Found an answer here Getting DOM node from React child element

The answer is slightly old so I rewrote a bit of it with callback refs instead of using findDOMNode (https://github.com/yannickcr/eslint-plugin-react/issues/678).

ParentComponent extends React.Component {
  constructor() {
    this.myRef = React.createRef();
  }

  render() {
    return (
    <ChildComponent>
      <div ref={myRef}>Blah</div>
    <ChildComponent>
    );
  }
}

ChildComponent extends React.Component {

  constructor() {
    this.myElement = null;
    this.myRef = element => {
      this.myElement = element;
    };
  }

  render() {
    const {children} = this.props.children;
    return (
    <div> 
     {React.cloneElement(children, { ref: this.myRef})};
    </div>
    )
  }
}

Note: the above only works with child component only having child from parent

Evan
  • 222
  • 3
  • 9