How to get a link from the React 16 portal?

Is there any way to get refReact 16 from the portal? I tried the following approach, but it does not work:

const Tooltip = props => (
  ReactDOM.createPortal(
    <div>{props.children}</div>,
    // A DOM element
    document.body
  )
);

class Info extends React.Component {
   render() {
      return (
        <Tooltip 
          ref={ el => this.tooltip = el }
        >
          My content
        </Tooltip>
      ); 
   }

   componentDidMount() {
      console.log(this.tooltip); // undefined
   }
}

I need refto dynamically calculate the end position of an element!

https://codepen.io/anon/pen/QqmBpB

+6
source share
2 answers

ReactDOM.createPortalreturns an instance of ReactPortal , which is a valid ReactNode but not a valid DOM element. At the same time, the createPortalcomponent context will be respected. So I moved the function call inside the rendering method and solved the problem.

class Info extends React.Component {
  render() {
    // I moved the portal creation to be here
    return ReactDOM.createPortal(
       // A valid DOM node!!
       <div ref={ el => this.tooltip = el }>{props.children}</div>,
       // A DOM element
       document.body
    ); 
  }

  componentDidMount() {
     console.log(this.tooltip); // HTMLDivElement
  }
}
+6
source

this.tooltip.props.children App Tooltip:

const appRoot = document.getElementById('app-root');
const tooltipRoot = document.getElementById('tooltip-root');

class Tooltip extends Component {
  constructor(props) {
    super(props);
    // Create a div that we'll render the Tooltip into
    this.el = document.createElement('div');
  }

  componentDidMount() {
    // Append the element into the DOM on mount.
    tooltipRoot.appendChild(this.el);
  }

  componentWillUnmount() {
    // Remove the element from the DOM when we unmount
    tooltipRoot.removeChild(this.el);
  }

  render() {
    // Use a portal to render the children into the element
    return ReactDOM.createPortal(
      // Any valid React child: JSX, strings, arrays, etc.
      this.props.children,
      // A DOM element
      this.el,
    );
  }
}

class App extends React.Component {
      componentDidMount() {
        console.log(this.tooltip.props.children);
      }
      render() {
        return (
          <div>
            <Tooltip ref={ el => this.tooltip = el }>
              My content
            </Tooltip>
          </div>
        );
      }
    }

ReactDOM.render(<App />, appRoot);

https://codepen.io/jorgemcdev/pen/aLYRVQ, https://codepen.io/gaearon/pen/jGBWpE

0

Source: https://habr.com/ru/post/1687138/


All Articles