Skip to content

Instantly share code, notes, and snippets.

@jordanrios94
Last active October 14, 2018 18:23
Show Gist options
  • Save jordanrios94/6c424c26a66ddd49eceedde708e8e926 to your computer and use it in GitHub Desktop.
Save jordanrios94/6c424c26a66ddd49eceedde708e8e926 to your computer and use it in GitHub Desktop.
React Portals

Portals

What is it?

Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.

Example

index.html

<div>
    <div id="root"></div>
    <div id="modal"></div>
</div>

Modal.js

const Modal = ({ children }) => {
  return ReactDOM.createPortal(children, document.getElementById('modal'));
};

AboutPage.js

class AboutPage extends Component {
  state = { modalOpened: true };
  toggleModal = () =>
    this.setState({
      modalOpened: !this.state.modalOpened
    });
  render() {
    const { modalOpened } = this.state;
    return (
      <div>
        <h1>About Us</h1>
        <button onClick={this.toggleModal}>toggle modal</button>
        {modalOpened && <Modal>Content inside of modal</Modal>}
      </div>
    );
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment