0.0.1 • Published 3 years ago

@yututi/react-imperative-dialog-hook-factory v0.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
3 years ago

React imperative dialog hook

A sample implementaion of dialog component using react hook that can use imperative.

Installation

npm i @yututi/react-imperative-dialog-hook-factory

Usage

This library does not provide hook. You can implement hooks via createDialogHook. A sample implementation is below.

  1. Define frame part of dialog.

    import { createDialogHook } from "@yututi/react-imperative-dialog-hook-factory"
    
    export const createDefaultDialogHook = function(render) {
      return createDialogHook({
        render,
        renderFrame: (close, node) => (
          <div className="dialog">
            <div className="dialog__header">
              <span className="close" onClick={() => {close({ok:false})}}>[x]</span>
            </div>
            <div className="dialog__body">
              {node}
            </div>
          </div>
        )
      })
    }
  2. Create useDialog hook.

    const useOkOrCancelDialog = createDefaultDialogHook(close => {
    
    const onOk = () => {
      close({ok: true})
    }
    
    const onCancel = () => {
      close({ok: false})
    }
    
    return (
      <div>
        This is sample dialog.
        <div className="actions">
          <button onClick={onCancel}>Cancel</button>
          <button onClick={onOk}>OK</button>
        </div>
      </div>
      )
    })
  3. Use hook in your component.

    const App = () => {
    
      const [text, setText] = useState("")
    
      const [dialog, openDialog] = useOkOrCancelDialog()
    
      const openDialogAndDispResult = () => {
        openDialog().then(result => {
          setText(result.ok ? "OK!" : "Cancel...")
        })
      }
    
      return (
        <div>
          <button onClick={openDialogAndDispResult}>open dialog</button>
          <div>{text}</div>
          {dialog}
        </div>
      )
    }