Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new CloseButton component and useClose hook #3096

Merged
merged 6 commits into from
Apr 12, 2024

Conversation

RobinMalfait
Copy link
Collaborator

@RobinMalfait RobinMalfait commented Apr 12, 2024

This PR adds a new CloseButton component to Headless UI as well as a new useClose hook.

These can be used inside a Dialog, Disclosure or Popover component and will close it when used.

Both the button and the hook are forgiving, meaning if you use them outside of a "closable" component they will do nothing.

CloseButton component

Use the CloseButton component within a "closable" component to automatically close it when the button is clicked:

import { CloseButton } from '@headlessui/react'

<MyDialog>
  /* ... */
  <CloseButton>
    Close
  </CloseButton>
<MyDialog>

This component also supports the as prop allowing you to wrap an existing component with it:

import { CloseButton } from '@headlessui/react'
import { MyButton, MyDialog } from './components'

<MyDialog>
  /* ... */
  <CloseButton as={MyButton}>
    Close
  </CloseButton>
<MyDialog>

useClose Hook

The useClose hook is useful in situations where you need more control over when the "closable" component is closed. For example, maybe you want to close a dialog when you submit a form within it:

import { Dialog, useClose } from '@headlessui/react'

export function MySearchForm() {
  let close = useClose()

  return (
    <form
      onSubmit={(event) => {
        event.preventDefault()
        /* perform search... */          
        close()
      }}
    >
      <input type="search" />
    </form>
    /* ... */
  )
}

export function MyDialog() {
  return (
    <Dialog>
      <MySearchForm />
      /* ... */
    </Dialog>
  )
}

Copy link

vercel bot commented Apr 12, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
headlessui-react ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 12, 2024 9:15am
headlessui-vue ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 12, 2024 9:15am

Copy link
Member

@reinink reinink left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me @RobinMalfait! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants