Socket
Socket
Sign inDemoInstall

react-useportal

Package Overview
Dependencies
9
Maintainers
1
Versions
49
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    react-useportal

🌀 React hook for Portals


Version published
Maintainers
1
Created

Readme

Source

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 otherwise you will need to attach a ref to the clicked element.

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

  return {
    Modal: Portal,
    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. i.e. onClick={e => openPortal(e)}

Options

OptionDescription
closeOnOutsideClickThis will close the portal when not clicking within the portal. Default is true
closeOnEscThis will allow you to hit ESC and it will close the modal. Default is true
bindToThis is the DOM node you want to attach the portal to. By default it attaches to document.body
isOpenThis will be the default for the portal. Default is false
onOpenThis is used to call something when the portal is opened and to modify the css of the portal directly
onCloseThis is used to call something when the portal is closed and to modify the css of the portal directly
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,
  ref, // 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
} = usePortal({
  closeOnOutsideClick: true,
  closeOnEsc: true,
  bindTo, // attach the portal to this node in the DOM
  isOpen: false,
  onOpen: ({ event, portal, targetEl }) => {},
  onClose({ event, portal, targetEl }) {},
  // in addition, any event handler such as onClick, onMouseOver, etc will be handled like
  onClick({ event, portal, targetEl }) {}
})

Todos

  • 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
  • make work without requiring the html synthetic event
  • add example for tooltip (like this one)
  • add as many examples as possible 😊
  • fix code so maintainability is A
  • set up code climate test coverage
  • optimize badges see awesome badge list
    • add code climate test coverage badge
  • document when you are required to have synthetic event
  • make isomorphic
  • continuous integration
  • greenkeeper

Keywords

FAQs

Last updated on 18 Sep 2019

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc