PavlMais / use-portal-hook

Super simple react hook for Portals

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use Portal Hook

build npm version

Features

  • Type safe
  • Small size
  • Zero dependencies
  • Simple API

Quick Start

Install

npm i use-portal-hook

Add a provider

import { PortalProvider } from "use-portal-hook";
...
root.render(
  <PortalProvider>
    <App />
  </PortalProvider>
)

Create a modal

import { PortalComponent } from "use-portal-hook";

interface DeleteModalProps {
  title: string
}

export const DeleteModal: PortalComponent<DeleteModalProps, boolean> = ({ onClose, props }) => {
  return (
    <div>
      {props.title}
      <button onClick={() => onClose(false)}>Cancel</button>
      <button onClick={() => onClose(true)}>Delete</button>
    </div>
  )
}

Use the modal

import { usePortal } from "use-portal-hook";
import { DeleteModal } from "./delete-modal";


const App = () => {
  const showDeleteModal = usePortal(DeleteModal);

  const handleDelete = async () => {
    const confirmed = await showDeleteModal({ title: 'Delete' })
    console.log('Confirmed: ', confirmed)
  }

  return (
    <button onClick={handleDelete}>Delete Item</button>
  );
}

Examples

License

MIT

About

Super simple react hook for Portals


Languages

Language:TypeScript 88.9%Language:HTML 8.3%Language:JavaScript 2.8%