Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/outside-click-ref.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'react-simplikit': minor
---

Add `useOutsideClickRef`, which returns a callback ref and calls `onOutsideClick` when a click happens outside every element the ref is attached to. One ref can be shared by a trigger and its menu, so the elements no longer need their own state. Pass `enabled: false` to stop listening, for example while the menu is closed. A pointer press that starts inside and is released outside is not treated as an outside click.
3 changes: 2 additions & 1 deletion .scripts/commands/generateSkill/template.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: react-simplikit
description: Selects and applies react-simplikit hooks, components and utils (useDebouncedCallback, useThrottledCallback, useToggle, useBooleanState, useCounter, useList, useMap, useSet, useInterval, useTimeout, usePrevious, usePreservedCallback, useOutsideClickEffect, useIntersectionObserver, useStorageState, useLongPress, SwitchCase, Separated, mergeRefs, buildContext, ...) instead of hand-written equivalents, including the mobile-web keyboard, safe-area, visual viewport and body-scroll-lock hooks. Use when writing React state or effect logic, debouncing or throttling, boolean/counter/list/map/set state, intervals and timeouts, click-outside, long-press or double-click handling, viewport visibility or impression tracking, persisted state in localStorage/sessionStorage, conditional rendering, merging refs, React Context boilerplate, or SSR-safe browser access, and whenever the project depends on react-simplikit.
description: Selects and applies react-simplikit hooks, components and utils (useDebouncedCallback, useThrottledCallback, useToggle, useBooleanState, useCounter, useList, useMap, useSet, useInterval, useTimeout, usePrevious, usePreservedCallback, useOutsideClickEffect, useOutsideClickRef, useIntersectionObserver, useStorageState, useLongPress, SwitchCase, Separated, mergeRefs, buildContext, ...) instead of hand-written equivalents, including the mobile-web keyboard, safe-area, visual viewport and body-scroll-lock hooks. Use when writing React state or effect logic, debouncing or throttling, boolean/counter/list/map/set state, intervals and timeouts, click-outside, long-press or double-click handling, viewport visibility or impression tracking, persisted state in localStorage/sessionStorage, conditional rendering, merging refs, React Context boilerplate, or SSR-safe browser access, and whenever the project depends on react-simplikit.
license: MIT
metadata:
author: toss
Expand Down Expand Up @@ -40,6 +40,7 @@ Backticks in this table mark catalog entries only.
| Effect that runs only when a condition holds | `useConditionalEffect` |
| Side effect tied to a DOM ref (attach/detach) | `useRefEffect` |
| Click / tap outside an element (close menu, modal) | `useOutsideClickEffect` |
| Click / tap outside a trigger and its menu sharing one ref | `useOutsideClickRef` |
| Long press / double click | `useLongPress` / `useDoubleClick` |
| Element enters or leaves the viewport | `useIntersectionObserver` |
| How long an element stayed visible (impression tracking) | `useImpressionRef` / `ImpressionArea` |
Expand Down
1 change: 1 addition & 0 deletions docs/es/use-cases.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Llama a los Hooks en el nivel superior de un componente React o de un Hook perso
| Limitar la frecuencia de un callback | [useThrottledCallback](/es/hooks/useThrottledCallback) | Un callback con frecuencia limitada al intervalo configurado |
| Conservar el estado al recargar | [useStorageState](/es/hooks/useStorageState) | Estado persistido en el almacenamiento del navegador |
| Responder a un clic fuera de un elemento | [useOutsideClickEffect](/es/hooks/useOutsideClickEffect) | Una suscripción a clics externos |
| Cerrar un menú con un clic externo | [useOutsideClickRef](/es/hooks/useOutsideClickRef) | Una única ref compartida por el activador y su menú |
| Mantener un campo sobre el teclado | [useAvoidKeyboard](/es/hooks/useAvoidKeyboard) | Un estilo para posicionar un elemento fijo |
| Insertar separadores entre hijos | [Separated](/es/components/Separated) | Separadores sin uno al final |
| Conectar varias refs a un elemento | [mergeRefs](/es/utils/mergeRefs) | Un único callback de ref que pasa el elemento a cada ref |
Expand Down
1 change: 1 addition & 0 deletions docs/ja/use-cases.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ description: 解決したい問題に合う React ユーティリティを選ぶ
| コールバックの呼び出し頻度を制限する | [useThrottledCallback](/ja/hooks/useThrottledCallback) | 指定した間隔で呼び出し頻度を制限するコールバック |
| 再読み込み後も状態を保持する | [useStorageState](/ja/hooks/useStorageState) | ブラウザストレージに保存される状態 |
| 要素の外側のクリックに反応する | [useOutsideClickEffect](/ja/hooks/useOutsideClickEffect) | 外側のクリックの購読 |
| 外側のクリックでメニューを閉じる | [useOutsideClickRef](/ja/hooks/useOutsideClickRef) | トリガーとメニューで共有する 1 つの ref |
| 入力欄をキーボードの上に保つ | [useAvoidKeyboard](/ja/hooks/useAvoidKeyboard) | 固定要素の位置を調整するスタイル |
| 子要素の間に区切りを入れる | [Separated](/ja/components/Separated) | 末尾には付かない区切り |
| 1 つの要素に複数の ref を接続する | [mergeRefs](/ja/utils/mergeRefs) | 各 ref に要素を渡す 1 つの ref コールバック |
Expand Down
1 change: 1 addition & 0 deletions docs/ko/use-cases.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ description: 해결하려는 문제에 맞는 React 유틸리티 선택하기
| 콜백 호출 빈도 제한하기 | [useThrottledCallback](/ko/hooks/useThrottledCallback) | 설정한 간격으로 호출 빈도를 제한하는 콜백 |
| 새로고침 후에도 상태 유지하기 | [useStorageState](/ko/hooks/useStorageState) | 브라우저 저장소에 유지되는 상태 |
| 요소 바깥 클릭에 반응하기 | [useOutsideClickEffect](/ko/hooks/useOutsideClickEffect) | 요소 바깥 클릭 구독 |
| 바깥 클릭으로 메뉴 닫기 | [useOutsideClickRef](/ko/hooks/useOutsideClickRef) | 트리거와 메뉴가 함께 쓰는 하나의 ref |
| 입력창을 키보드 위에 유지하기 | [useAvoidKeyboard](/ko/hooks/useAvoidKeyboard) | 고정 요소의 위치를 조절하는 스타일 |
| 자식 요소 사이에 구분자 넣기 | [Separated](/ko/components/Separated) | 마지막 요소 뒤에는 붙지 않는 구분자 |
| 한 요소에 여러 ref 연결하기 | [mergeRefs](/ko/utils/mergeRefs) | 각 ref에 요소를 전달하는 하나의 ref 콜백 |
Expand Down
1 change: 1 addition & 0 deletions docs/use-cases.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Call hooks at the top level of a React component or custom hook. In a framework
| Limit callback frequency | [useThrottledCallback](/hooks/useThrottledCallback) | A callback limited to the configured interval |
| Keep state across reloads | [useStorageState](/hooks/useStorageState) | State persisted in browser storage |
| React to a click outside an element | [useOutsideClickEffect](/hooks/useOutsideClickEffect) | An outside-click subscription |
| Close a menu on an outside click | [useOutsideClickRef](/hooks/useOutsideClickRef) | One ref shared by the trigger and its menu |
| Keep an input above the keyboard | [useAvoidKeyboard](/hooks/useAvoidKeyboard) | A style for positioning a fixed element |
| Insert separators between children | [Separated](/components/Separated) | Separators without a trailing separator |
| Attach multiple refs to one element | [mergeRefs](/utils/mergeRefs) | One ref callback that passes the element to each ref |
Expand Down
1 change: 1 addition & 0 deletions docs/zh-Hans/use-cases.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ description: 根据要解决的问题选择 React 工具函数
| 限制回调频率 | [useThrottledCallback](/zh-Hans/hooks/useThrottledCallback) | 按设定间隔限制调用频率的回调 |
| 刷新后保留状态 | [useStorageState](/zh-Hans/hooks/useStorageState) | 保存在浏览器存储中的状态 |
| 响应元素外部的点击 | [useOutsideClickEffect](/zh-Hans/hooks/useOutsideClickEffect) | 元素外部点击订阅 |
| 点击外部时关闭菜单 | [useOutsideClickRef](/zh-Hans/hooks/useOutsideClickRef) | 触发按钮和菜单共用的一个 ref |
| 让输入框保持在键盘上方 | [useAvoidKeyboard](/zh-Hans/hooks/useAvoidKeyboard) | 用于定位固定元素的样式 |
| 在子元素之间插入分隔符 | [Separated](/zh-Hans/components/Separated) | 末尾没有分隔符 |
| 为一个元素连接多个 ref | [mergeRefs](/zh-Hans/utils/mergeRefs) | 将元素传递给各个 ref 的单个 ref 回调 |
Expand Down
4 changes: 3 additions & 1 deletion packages/plugin/skills/react-simplikit/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: react-simplikit
description: Selects and applies react-simplikit hooks, components and utils (useDebouncedCallback, useThrottledCallback, useToggle, useBooleanState, useCounter, useList, useMap, useSet, useInterval, useTimeout, usePrevious, usePreservedCallback, useOutsideClickEffect, useIntersectionObserver, useStorageState, useLongPress, SwitchCase, Separated, mergeRefs, buildContext, ...) instead of hand-written equivalents, including the mobile-web keyboard, safe-area, visual viewport and body-scroll-lock hooks. Use when writing React state or effect logic, debouncing or throttling, boolean/counter/list/map/set state, intervals and timeouts, click-outside, long-press or double-click handling, viewport visibility or impression tracking, persisted state in localStorage/sessionStorage, conditional rendering, merging refs, React Context boilerplate, or SSR-safe browser access, and whenever the project depends on react-simplikit.
description: Selects and applies react-simplikit hooks, components and utils (useDebouncedCallback, useThrottledCallback, useToggle, useBooleanState, useCounter, useList, useMap, useSet, useInterval, useTimeout, usePrevious, usePreservedCallback, useOutsideClickEffect, useOutsideClickRef, useIntersectionObserver, useStorageState, useLongPress, SwitchCase, Separated, mergeRefs, buildContext, ...) instead of hand-written equivalents, including the mobile-web keyboard, safe-area, visual viewport and body-scroll-lock hooks. Use when writing React state or effect logic, debouncing or throttling, boolean/counter/list/map/set state, intervals and timeouts, click-outside, long-press or double-click handling, viewport visibility or impression tracking, persisted state in localStorage/sessionStorage, conditional rendering, merging refs, React Context boilerplate, or SSR-safe browser access, and whenever the project depends on react-simplikit.
license: MIT
metadata:
author: toss
Expand Down Expand Up @@ -40,6 +40,7 @@ Backticks in this table mark catalog entries only.
| Effect that runs only when a condition holds | `useConditionalEffect` |
| Side effect tied to a DOM ref (attach/detach) | `useRefEffect` |
| Click / tap outside an element (close menu, modal) | `useOutsideClickEffect` |
| Click / tap outside a trigger and its menu sharing one ref | `useOutsideClickRef` |
| Long press / double click | `useLongPress` / `useDoubleClick` |
| Element enters or leaves the viewport | `useIntersectionObserver` |
| How long an element stayed visible (impression tracking) | `useImpressionRef` / `ImpressionArea` |
Expand Down Expand Up @@ -98,6 +99,7 @@ Backticks in this table mark catalog entries only.
| [`useMap`](references/useMap.md) | A React hook that manages a key-value Map as state. |
| [`useNetworkStatus`](references/useNetworkStatus.md) | `useNetworkStatus` is a React hook that provides access to the Network Information API. |
| [`useOutsideClickEffect`](references/useOutsideClickEffect.md) | `useOutsideClickEffect` is a React hook that triggers a callback when a click event occurs outside the specified container(s). |
| [`useOutsideClickRef`](references/useOutsideClickRef.md) | `useOutsideClickRef` is a React hook that returns a callback ref and calls `onOutsideClick` when a click happens outside every element the ref is attached to. |
| [`usePageVisibility`](references/usePageVisibility.md) | `usePageVisibility` is a React hook that detects page visibility changes. |
| [`usePageVisibilityEffect`](references/usePageVisibilityEffect.md) | `usePageVisibilityEffect` is a React hook that listens to changes in the document's visibility state and triggers a callback. |
| [`usePreservedCallback`](references/usePreservedCallback.md) | `usePreservedCallback` is a React hook that maintains a stable reference to a callback function while ensuring it always has access to the latest state or props. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

`useOutsideClickEffect` is a React hook that triggers a callback when a click event occurs outside the specified container(s).
It is useful for closing modals, dropdowns, tooltips, and other UI components when clicking outside.
To treat several elements as inside without keeping each of them in state, use [`useOutsideClickRef`](/hooks/useOutsideClickRef), which returns one ref to attach to all of them.

## Interface

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# useOutsideClickRef

`useOutsideClickRef` is a React hook that returns a callback ref and calls `onOutsideClick` when a click happens outside every element the ref is attached to.
Attach the same ref to a trigger, its menu and any portal content, and a press that starts inside and ends outside is not counted as an outside click.

## Interface

```ts
function useOutsideClickRef(options: Object): (element: Element | null) => void;
```

### Parameters

<Interface
required
name="options"
type="Object"
description="Options for detecting outside clicks."
:nested="[
{
name: 'options.onOutsideClick',
type: '() => void',
required: true,
description:
'A function that is executed when a click happens outside every attached element. It runs before the clicked element\'s own <code>onClick</code>.',
},
{
name: 'options.enabled',
type: 'boolean',
required: false,
defaultValue: 'true',
description:
'Whether to detect outside clicks. While <code>false</code>, <code>onOutsideClick</code> is not called.',
},
]"
/>

### Return Value

<Interface
name=""
type="(element: Element | null) => void"
description="A callback ref to pass to the <code>ref</code> attribute of each element that counts as inside. It keeps the same identity across renders."
/>

## Example

```tsx
import { useOutsideClickRef } from 'react-simplikit';
import { useState } from 'react';

function Dropdown({ onClose }: { onClose: () => void }) {
const [open, setOpen] = useState(false);
const ref = useOutsideClickRef({
enabled: open,
onOutsideClick: () => {
setOpen(false);
onClose();
},
});

return (
<>
<button ref={ref} onClick={() => setOpen(prev => !prev)}>
Menu
</button>
{open && <ul ref={ref}>...</ul>}
</>
);
}
```
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

`useOutsideClickEffect` es un Hook de React que ejecuta un callback cuando ocurre un evento de clic fuera de los contenedores especificados.
Es útil para cerrar modales, menús desplegables, descripciones emergentes y otros componentes de la interfaz cuando haces clic fuera de ellos.
Para que varios elementos cuenten como interiores sin guardar cada uno de ellos en el estado, usa [`useOutsideClickRef`](/es/hooks/useOutsideClickRef), que devuelve una única ref que conectas a todos ellos.

## Interfaz

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

`useOutsideClickEffect` は、指定したコンテナーの外側でクリックイベントが発生したときにコールバックを実行する React フックです。
外側のクリックでモーダル、ドロップダウン、ツールチップなどの UI コンポーネントを閉じる場合に役立ちます。
複数の要素をそれぞれ状態に保持せずに内側として扱うには、それらすべてに接続する 1 つの ref を返す [`useOutsideClickRef`](/ja/hooks/useOutsideClickRef) を使ってください。

## インターフェース

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# useOutsideClickEffect

`useOutsideClickEffect`는 지정한 컨테이너 외부에서 클릭 이벤트가 발생하면 콜백을 실행하는 리액트 훅이에요. 외부를 클릭했을 때 모달, 드롭다운, 툴팁 같은 UI 컴포넌트를 닫는 데 유용해요.
`useOutsideClickEffect`는 지정한 컨테이너 외부에서 클릭 이벤트가 발생하면 콜백을 실행하는 리액트 훅이에요. 외부를 클릭했을 때 모달, 드롭다운, 툴팁 같은 UI 컴포넌트를 닫는 데 유용해요. 버튼과 메뉴처럼 여러 요소를 한 영역으로 묶고 그 바깥을 클릭했을 때 콜백을 실행하려면, 모든 요소에 연결할 ref 하나를 반환하는 [`useOutsideClickRef`](/ko/hooks/useOutsideClickRef)를 사용하세요.

## 인터페이스

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

`useOutsideClickEffect` is a React hook that triggers a callback when a click event occurs outside the specified container(s).
It is useful for closing modals, dropdowns, tooltips, and other UI components when clicking outside.
To treat several elements as inside without keeping each of them in state, use [`useOutsideClickRef`](/hooks/useOutsideClickRef), which returns one ref to attach to all of them.

## Interface

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ type OneOrMore<T> = T | T[];
* @description
* `useOutsideClickEffect` is a React hook that triggers a callback when a click event occurs outside the specified container(s).
* It is useful for closing modals, dropdowns, tooltips, and other UI components when clicking outside.
* To treat several elements as inside without keeping each of them in state, use [`useOutsideClickRef`](/hooks/useOutsideClickRef), which returns one ref to attach to all of them.
*
* @param {HTMLElement | (HTMLElement | null)[] | null} container - A single HTML element, an array of HTML elements or `null` values, or `null`.
* `null` entries are ignored. If no HTML elements remain, the callback is not executed.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# useOutsideClickEffect

`useOutsideClickEffect` 是一个在点击事件发生于指定容器之外时触发回调的 React Hook。它适用于在点击外部时关闭模态框、下拉菜单、工具提示以及其他 UI 组件。
`useOutsideClickEffect` 是一个在点击事件发生于指定容器之外时触发回调的 React Hook。它适用于在点击外部时关闭模态框、下拉菜单、工具提示以及其他 UI 组件。如果要将多个元素视为内部,又不想把每个元素都保存在状态中,可以使用 [`useOutsideClickRef`](/zh-Hans/hooks/useOutsideClickRef),它会返回一个可附加到所有这些元素上的 ref。

## 接口

Expand Down
Loading
Loading