Skip to content

developit/preact-portal

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ba21279 Β· Dec 7, 2018

History

19 Commits
Oct 31, 2018
Jan 29, 2018
Mar 5, 2016
Mar 5, 2016
Mar 5, 2016
Mar 5, 2016
Mar 5, 2016
Mar 5, 2016
Aug 31, 2016
Mar 5, 2016
Mar 7, 2016
Mar 5, 2016
Apr 9, 2018
Mar 5, 2016

Repository files navigation

🌌 preact-portal 🌠

NPM travis-ci

Render Preact components into SPACE*

* a space in the DOM. Sorry.

Use this if you have a component that needs to render children into some other place in the DOM.

An example of this would be modal dialogs, where you may need to render <Dialog /> into <body>.

Demo #1 Demo #2
Moving around the DOM by changing into. Open a full-page modal from within a thumbnail.

Installation

Via npm:

npm install --save preact-portal

Usage

import { h, Component, render } from 'preact';
import Portal from 'preact-portal';

class Thumbnail extends Component {
  open = () => this.setState({ open:true });
  close = () => this.setState({ open:false });

  render({ url }, { open }) {
    return (
      <div class="thumb" onClick={this.open}>
        <img src={url} />

        { open ? (
          <Portal into="body">
            <div class="popup" onClick={this.close}>
              <img src={url} />
            </div>
          </Portal>
        ) : null }
      </div>
    );
  }
}

render(<Thumbnail url="//i.imgur.com/6Rp4hbs.gif" />, document.body);

Or, wrap up a very common case into a simple high order function:

const Popup = ({ open, into="body", children }) => (
  open ? <Portal into={into}>{ children }</Portal> : null
);

// Example: show popup on error.
class Form extends Component {
  render({}, { error }) {
    return (
      <form>
        <Popup open={error}>
          <p>Error: {error}</p>
        </Popup>
        ...etc
      </form>
    );
  }
}