From 06a54c9a5e5cc9eb2cb78a11cf5887003434f5a9 Mon Sep 17 00:00:00 2001 From: ngorin Date: Wed, 13 Sep 2023 18:12:16 +0300 Subject: [PATCH] feat: create useOnClickOutside hook --- .../useOnClickOutside/__tests__/Demo.tsx | 33 +++++++++++++++++++ .../__tests__/useOnClickOutside.test.tsx | 20 +++++++++++ .../utils/useOnClickOutside/index.ts | 2 ++ 3 files changed, 55 insertions(+) create mode 100644 src/components/utils/useOnClickOutside/__tests__/Demo.tsx create mode 100644 src/components/utils/useOnClickOutside/__tests__/useOnClickOutside.test.tsx diff --git a/src/components/utils/useOnClickOutside/__tests__/Demo.tsx b/src/components/utils/useOnClickOutside/__tests__/Demo.tsx new file mode 100644 index 0000000000..3d583ba75f --- /dev/null +++ b/src/components/utils/useOnClickOutside/__tests__/Demo.tsx @@ -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 ( +
+

{status}

+
+ {'Target'} +
+
{'Outside'}
+
+ ); +}; diff --git a/src/components/utils/useOnClickOutside/__tests__/useOnClickOutside.test.tsx b/src/components/utils/useOnClickOutside/__tests__/useOnClickOutside.test.tsx new file mode 100644 index 0000000000..ff396575b1 --- /dev/null +++ b/src/components/utils/useOnClickOutside/__tests__/useOnClickOutside.test.tsx @@ -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(); + + 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'); +}); diff --git a/src/components/utils/useOnClickOutside/index.ts b/src/components/utils/useOnClickOutside/index.ts index e69de29bb2..bd065fd97e 100644 --- a/src/components/utils/useOnClickOutside/index.ts +++ b/src/components/utils/useOnClickOutside/index.ts @@ -0,0 +1,2 @@ +export {useOnClickOutside} from './useOnClickOutside'; +export type {UseOnClickOutsideType} from './useOnClickOutside';