• Stars
    star
    890
  • Rank 51,052 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 5 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐ŸŒ€ React hook for Portals

usePortal

๐ŸŒ€ React hook for using Portals

undefined undefined undefined Known Vulnerabilities Known Vulnerabilities

Need to make dropdowns, lightboxes/modals/dialogs, global message notifications, or tooltips in React? React Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component (react docs).

This hook is also isomorphic, meaning it works with SSR (server side rendering).

Features

  • SSR (server side rendering) support
  • TypeScript support
  • 1 dependency (use-ssr)
  • Built in state

Examples

Installation

yarn add react-useportal      or     npm i -S react-useportal

Usage

Stateless

import usePortal from 'react-useportal'

const App = () => {
  const { Portal } = usePortal()

  return (
    <Portal>
      This text is portaled at the end of document.body!
    </Portal>
  )
}

const App = () => {
  const { Portal } = usePortal({
    bindTo: document && document.getElementById('san-francisco')
  })

  return (
    <Portal>
      This text is portaled into San Francisco!
    </Portal>
  )
}

With State

import usePortal from 'react-useportal'

const App = () => {
  var { openPortal, closePortal, isOpen, Portal } = usePortal()

  // want to use array destructuring? You can do that too
  var [openPortal, closePortal, isOpen, Portal] = usePortal()

  return (
    <>
      <button onClick={openPortal}>
        Open Portal
      </button>
      {isOpen && (
        <Portal>
          <p>
            This Portal handles its own state.{' '}
            <button onClick={closePortal}>Close me!</button>, hit ESC or
            click outside of me.
          </p>
        </Portal>
      )}
    </>
  )
}

Need Animations?

import usePortal from 'react-useportal'

const App = () => {
  const { openPortal, closePortal, isOpen, Portal } = usePortal()
  return (
    <>
      <button onClick={openPortal}>
        Open Portal
      </button>
      <Portal>
        <p className={isOpen ? 'animateIn' : 'animateOut'}>
          This Portal handles its own state.{' '}
          <button onClick={closePortal}>Close me!</button>, hit ESC or
          click outside of me.
        </p>
      </Portal>
    </>
  )
}

Customizing the Portal directly

By using onOpen, onClose or any other event handler, you can modify the Portal and return it. See useDropdown for a working example. It's important that you pass the event object to openPortal and togglePortal otherwise you will need to attach a ref to the clicked element.

const useModal = () => {
  const { isOpen, openPortal, togglePortal, closePortal, Portal } = usePortal({
    onOpen({ portal }) {
      portal.current.style.cssText = `
        /* add your css here for the Portal */
        position: fixed;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
        z-index: 1000;
      `
    }
  })

  return {
    Modal: Portal,
    openModal: openPortal,
    toggleModal: togglePortal,
    closeModal: closePortal,
    isOpen
  }
}

const App = () => {
  const { openModal, closeModal, isOpen, Modal } = useModal()
  
  return <>
    <button onClick={e => openModal(e)}>Open Modal<button>
    {isOpen && (
      <Modal>
        This will dynamically center to the middle of the screen regardless of the size of what you put in here
      </Modal>
    )}
  </>
}

Make sure you are passing the html synthetic event to the openPortal and togglePortal . i.e. onClick={e => openPortal(e)}

Usage with a ref

If for some reason, you don't want to pass around the event to openPortal or togglePortal, you can use a ref like this.

import usePortal from 'react-useportal'

const App = () => {
  var { ref, openPortal, closePortal, isOpen, Portal } = usePortal()

  return (
    <>
      {/* see below how I don't have to pass the event if I use the ref */}
      <button ref={ref} onClick={() => openPortal()}>
        Open Portal
      </button>
      {isOpen && (
        <Portal>
          <p>
            This Portal handles its own state.{' '}
            <button onClick={closePortal}>Close me!</button>, hit ESC or
            click outside of me.
          </p>
        </Portal>
      )}
    </>
  )
}

Options

Option Description
closeOnOutsideClick This will close the portal when not clicking within the portal. Default is true
closeOnEsc This will allow you to hit ESC and it will close the modal. Default is true
bindTo This is the DOM node you want to attach the portal to. By default it attaches to document.body
isOpen This will be the default for the portal. Default is false
onOpen This is used to call something when the portal is opened and to modify the css of the portal directly
onClose This is used to call something when the portal is closed and to modify the css of the portal directly
onPortalClick This is fired whenever clicking on the Portal
html event handlers (i.e. onClick) These can be used instead of onOpen to modify the css of the portal directly. onMouseEnter and onMouseLeave example

Option Usage

const {
  openPortal,
  closePortal,
  togglePortal,
  isOpen,
  Portal,
  // if you don't pass an event to openPortal, closePortal, or togglePortal, you will need
  // to put this on the element you want to interact with/click
  ref,
  // if for some reason you want to interact directly with the portal, you can with this ref
  portalRef,
} = usePortal({
  closeOnOutsideClick: true,
  closeOnEsc: true,
  bindTo, // attach the portal to this node in the DOM
  isOpen: false,
  // `event` has all the fields that a normal `event` would have such as `event.target.value`, etc.
  // with the additional `portal` and `targetEl` added to it as seen in the examples below
  onOpen: (event) => {
    // can access: event.portal, event.targetEl, event.event, event.target, etc.
  },
  // `onClose` will not have an `event` unless you pass an `event` to `closePortal`
  onClose({ portal, targetEl, event }) {},
  // `targetEl` is the element that you either are attaching a `ref` to
  // or that you are putting `openPortal` or `togglePortal` or `closePortal` on
  onPortalClick({ portal, targetEl, event }) {},
  // in addition, any event handler such as onClick, onMouseOver, etc will be handled the same
  onClick({ portal, targetEl, event }) {}
})

Todos

  • React Native support. 1 2 3 4 5 Probably going to have to add a Provider...
  • add correct typescript return types
  • add support for popup windows resource 1 resource 2. Maybe something like
  const { openPortal, closePortal, isOpen, Portal } = usePortal({
    popup: ['', '', 'width=600,height=400,left=200,top=200']
  })
  // window.open('', '', 'width=600,height=400,left=200,top=200')
  • tests (priority)
  • maybe have a <Provider order={['Portal', 'openPortal']} /> then you can change the order of the array destructuring syntax
  • fix code so maintainability is A
  • set up code climate test coverage
  • optimize badges see awesome badge list
    • add code climate test coverage badge

More Repositories

1

use-ssr

โ˜ฏ๏ธ React hook to determine if you are on the server, browser, or react native
TypeScript
261
star
2

fasthacks

โŒ˜ Speed hacks to increase productivity
JavaScript
170
star
3

Interviews

๐Ÿค“ Data structures in JS & interview questions/algorithms
JavaScript
138
star
4

use-react-modal

๐Ÿ–ผ React hook for Modals
TypeScript
80
star
5

alfred-workflows

A list of my favorite workflows for developers.
PHP
72
star
6

the-perfect-portfolio

This is my portfolio! :)
PHP
31
star
7

urs

useRefState, for getting correct values even when in callback functions, and blocking state updates on unmounted components
TypeScript
16
star
8

use-react-storage

๐Ÿ•‹ React hook for local storage on the server, browser, and react native
TypeScript
14
star
9

portfolio

Built with React, Relay, GraphQL, and all babel-node's ES2016 features!
JavaScript
13
star
10

email-autocomplete-input

โšก๏ธ Email autocomplete input
JavaScript
11
star
11

readme-template

๐Ÿ”ฅThe most awesome README template out there
10
star
12

react-css-to-js

This is a compiler that translates CSS into JS. (Currently Not Production Quality)
JavaScript
6
star
13

use-cursor

๐Ÿญ React hook for customizing the mouse
TypeScript
5
star
14

google-students

This is a template I built for different Google programs specialists to quickly and easily get a website up and running for their event. It's still in the workings so that it's even easier for people to build on, but it gets the job done in the time being.
CSS
5
star
15

mine-sweeper

๐Ÿ’ฃ Minesweeper
JavaScript
4
star
16

MuniModel

Java
1
star
17

vocaldash

PHP
1
star
18

alexcory.com

โ„๏ธMy portfolio website (WIP)
JavaScript
1
star
19

hacklete

The portfolio for all software engineers.
JavaScript
1
star
20

techtalksfsu

This is the website I created for Google Helpouts and the event at SFSU.
PHP
1
star
21

date-input

A simple date input for React.js
JavaScript
1
star
22

mvc-website

This is a website I built that uses a home made MVC framework. I built it from the ground up. The only thing I didn't build was the ADODB library I used to add and get posts to the database. The database used was MySQL (PHP MyAdmin).
PHP
1
star