Skip to content

Commit

Permalink
[@mantine/core] Popover: Add onClose and onOpen events supports f…
Browse files Browse the repository at this point in the history
…or uncontrolled popovers (mantinedev#3716)

Co-authored-by: Paul Moss <paulmoss06@gmail.com>
  • Loading branch information
paulm17 and Paul Moss authored Mar 14, 2023
1 parent 6d5df57 commit 993406a
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/mantine-core/src/Popover/Popover.story.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useState } from 'react';
import { Box } from '../Box';
import { Popover } from './Popover';
import { Button } from '../Button';
import { MultiSelect } from '../MultiSelect';
Expand Down Expand Up @@ -197,3 +198,51 @@ export function Inline() {
</div>
);
}

export function PopoverEvents() {
const [opened, setState] = useState(false);
const [toggle1, setToggle1] = useState(false);
const [toggle2, setToggle2] = useState(false);

return (
<div style={{ padding: 100, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<Group>
<Popover
opened={opened}
onChange={setState}
onOpen={() => setToggle1(true)}
onClose={() => setToggle1(false)}
middlewares={{ shift: false, flip: false }}
position="bottom"
withArrow
trapFocus
radius="md"
returnFocus
>
<Popover.Target>
<Box>
<Button onClick={() => setState((c) => !c)}>Toggle controlled popover</Button>
<br />
<div>Controlled State: {toggle1 ? 'Open' : 'Closed'}</div>
</Box>
</Popover.Target>

<Popover.Dropdown>
<Button onClick={() => setState(false)}>Close</Button>
</Popover.Dropdown>
</Popover>
<Popover onOpen={() => setToggle2(true)} onClose={() => setToggle2(false)}>
<Popover.Target>
<Box>
<Button>Toggle uncontrolled popover</Button>
<br />
<div>Uncontrolled State: {toggle2 ? 'Open' : 'Closed'}</div>
</Box>
</Popover.Target>

<Popover.Dropdown>Dropdown</Popover.Dropdown>
</Popover>
</Group>
</div>
);
}
8 changes: 8 additions & 0 deletions src/mantine-core/src/Popover/use-popover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,14 @@ export function usePopover(options: UsePopoverOptions) {
options.onPositionChange?.(floating.placement);
}, [floating.placement]);

useDidUpdate(() => {
if (!options.opened) {
options.onClose?.();
} else {
options.onOpen?.();
}
}, [options.opened]);

return {
floating,
controlled: typeof options.opened === 'boolean',
Expand Down

0 comments on commit 993406a

Please sign in to comment.