# useFocusTrap

*Category:* Utilities
*Section:* DOM behavior hooks
*Source:* https://uikit.developers.rio.cloud/#/utilities/useFocusTrap
*Captured:* 2026-04-27T14:59:34.932Z

This custom hook allows to keep the focus inside a defined wrapper element. This might be a dialog or a custom overlay.

## useFocusTrap

- When you have a external component that will be re-rendered after the overlay opens, you can use the built-in ref. This ref will be returned from this hook and can be set on the respective wrapper element.
- When you have an element that does not re-render, use a local state setter function to be set as the ref. This element can then be passed as a parameter to this hook and it will be used instead of the built-in ref.const [focusTrapRef, setFocusTrapRef] = useState<HTMLDivElement | null>(null); useFocusTrap(focusTrapRef); <div ref={setFocusTrapRef}>...</div>

### Example: Example 1

Open Dialog

#### React (tsx)

```tsx
import { useEffect, useRef, useState } from 'react';

import Dialog from '@rio-cloud/rio-uikit/Dialog';
import Button from '@rio-cloud/rio-uikit/Button';
import useFocusTrap from '@rio-cloud/rio-uikit/useFocusTrap';

const DemoBody = () => {
    const inputRef = useRef<HTMLInputElement>(null);

    const focusTrapRef = useFocusTrap();

    useEffect(() => {
        if (inputRef.current) {
            inputRef.current.focus();
        }
    }, [inputRef.current]);

    return (
        <div ref={focusTrapRef} className='form-group display-flex gap-10'>
            <input ref={inputRef} className='form-control' />
            <div className='btn-toolbar flex-nowrap'>
                <Button>Button 1</Button>
                <Button>Button 2</Button>
            </div>
        </div>
    );
};

export default () => {
    const [showDialog, setShowDialog] = useState(false);

    return (
        <div>
            <Dialog
                show={showDialog}
                onClose={() => setShowDialog(false)}
                title='Demo Focus Trap'
                showCloseButton
                bsSize='sm'
                body={<DemoBody />}
            />
            <Button onClick={() => setShowDialog(true)}>Open Dialog</Button>
        </div>
    );
};
```

#### HTML (html)

```html
<div>
    <button type="button" class="btn btn-default btn-component" tabindex="0">Open Dialog</button>
</div>
```

#### Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| element | HTMLDivElement \| null | — | The wrapper element that traps the focus. Use this if your component does not rerender, otherwise use the internal ref that gets returned from the hook. |