Search code examples
reactjsreact-dom

How to use React Portal?


I am trying to use React Portal functionality, but can't seem to get it to work (am using React v16.2 and ReactDOM v16.2). In the example below, when I click the 'click me' link 'yey!' should appear but it doesn't:

HTML:

<div id="app-root"></div>
<div id="toast-root"></div>

JavaScript:

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

const insertToast = (toastRoot) => ReactDOM.createPortal(
  'yey!',
  toastRoot,
); 

class App extends React.Component {

  insertToasts() {
    const toastRoot = document.getElementById('toast-root');
    insertToast(toastRoot);
  }

  render() {
    return (
      <div>
        <a onClick={this.insertToasts}>click me</a>
      </div>
    );
  }
}

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

Solution

  • In your example, you create and return the portal from insertToast, however, you don't do anything with it - you need to return it and ensure that it is included within your render method:

    const appRoot = document.getElementById('app-root');
    
    const insertToast = (toastRoot) => ReactDOM.createPortal(
        'This is in toast-root - yey!',
        toastRoot,
    );
    
    class App extends React.Component {
    
        insertToasts() {
            const toastRoot = document.getElementById('toast-root');
            return insertToast(toastRoot);
        }
    
        render() {
            return (
                <div>
                    <div>This is in app-root.</div>
                    {this.insertToasts()}
                </div>
            );
        }
    }
    
    ReactDOM.render(<App />, appRoot);
    

    Even if it's not being rendered in the same DOM as the component, you still have to tell React that you want to render it.