Skip to content

Commit

Permalink
feat: create useOnClickOutside hook
Browse files Browse the repository at this point in the history
  • Loading branch information
NikitaCG committed Sep 13, 2023
1 parent e1d2192 commit 06a54c9
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/components/utils/useOnClickOutside/__tests__/Demo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/* eslint-disable jsx-a11y/click-events-have-key-events */
import React from 'react';

import {useOnClickOutside} from '../useOnClickOutside';

export const Demo = () => {
const observerRef = React.useRef(null);
const [status, setStatus] = React.useState<1 | 0>(0);

const handleOutsideClick = () => {
setStatus(0);
};

const handleClick = () => {
setStatus(1);
};

useOnClickOutside({
observedRef: observerRef,
enabled: true,
handleCallback: handleOutsideClick,
});

return (
<div>
<h1>{status}</h1>
<div ref={observerRef} onClick={handleClick}>
{'Target'}
</div>
<div>{'Outside'}</div>
</div>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import React from 'react';

import {render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';

import {Demo} from './Demo';

test('Check useOnClickOutside correct work', async () => {
render(<Demo />);

expect(screen.getByRole('heading')).toHaveTextContent('0');

await userEvent.click(screen.getByText('Target'));

expect(screen.getByRole('heading')).toHaveTextContent('1');

await userEvent.click(screen.getByText('Outside'));

expect(screen.getByRole('heading')).toHaveTextContent('0');
});
2 changes: 2 additions & 0 deletions src/components/utils/useOnClickOutside/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export {useOnClickOutside} from './useOnClickOutside';
export type {UseOnClickOutsideType} from './useOnClickOutside';

0 comments on commit 06a54c9

Please sign in to comment.