> ## Documentation Index
> Fetch the complete documentation index at: https://docs.twenty.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Выбор валюты

> Выберите валюту с помощью полного средства выбора или скомпонуйте его части в раскрывающемся списке.

## Обзор

`CurrencyPicker` объединяет компактный триггер валюты, доступные для поиска параметры и [Dropdown](https://docs.twenty.com/ru/ui/components/navigation/dropdown.md). Предоставьте каталог валют и используйте один компонент для обычного выбора. Скомпонуйте `Root`, `Trigger` и `Options` с Dropdown, когда во всплывающем окне требуется другое содержимое или страницы.

**Light**

[Выбор валюты (light)](https://storybook.twenty.com/iframe.html?id=ui-input-currencypicker--display\&viewMode=story\&globals=colorScheme:light)

**Dark**

[Выбор валюты (dark)](https://storybook.twenty.com/iframe.html?id=ui-input-currencypicker--display\&viewMode=story\&globals=colorScheme:dark)

[Open in Storybook](https://storybook.twenty.com/?path=/story/ui-input-currencypicker--display)

## Использование

Каждая валюта имеет уникальный `code`, `name` и необязательные свойства `symbol` и `disabled`. Код является стабильным идентификатором выбора. Средство выбора не поставляется с каталогом валют и не выбирает значение приложения по умолчанию.

```tsx theme={null}
import { CurrencyPicker } from 'twenty-ui/components/input';

const CURRENCIES = [
  { code: 'EUR', name: 'Euro', symbol: '€' },
  { code: 'USD', name: 'US Dollar', symbol: '$' },
];

export const InvoiceCurrency = () => (
  <CurrencyPicker
    currencies={CURRENCIES}
    defaultValue="USD"
    aria-label="Invoice currency"
    optionsProps={{
      searchLabel: 'Search currencies',
      emptyLabel: 'No currencies found',
    }}
    contentProps={{ width: 280 }}
  />
);
```

Используйте `defaultValue` для неконтролируемого выбора. Для контролируемого выбора передайте `value` и обновляйте его из `onValueChange`. Колбэк получает следующий код или `null`, а также сведения о выборе Dropdown, содержащие `event`, `reason`, `trigger`, `cancel` и `isCanceled`. Вызовите `details.cancel()`, чтобы сохранить текущий выбор и оставить всплывающее окно открытым. Выбор текущего кода не вызывает ещё одного изменения.

`null` очищает выбор. Пустая строка остаётся допустимым кодом и не очищает его. Неизвестное значение остаётся неизменным и отображается в триггере как необработанный код; оно не добавляет параметр в каталог. Последующее контролируемое обновление или изменение каталога обновляет триггер и выбранную строку.

```tsx theme={null}
import { useState } from 'react';
import { CurrencyPicker } from 'twenty-ui/components/input';
import { Button } from 'twenty-ui/primitives/input';

const CURRENCIES = [
  { code: 'EUR', name: 'Euro' },
  { code: 'USD', name: 'US Dollar' },
];

export const ClearableCurrency = () => {
  const [value, setValue] = useState<string | null>('USD');

  return (
    <>
      <CurrencyPicker
        currencies={CURRENCIES}
        value={value}
        onValueChange={setValue}
        aria-label="Invoice currency"
        triggerProps={{ placeholder: 'Choose a currency' }}
      />
      <Button onClick={() => setValue(null)}>Clear currency</Button>
    </>
  );
};
```

## Расширенная композиция

`CurrencyPicker.Root` подготавливает каталог и управляет выбором для обеих частей. Он не добавляет элемент DOM и должен находиться внутри `Dropdown.Root`. Размещайте `Trigger` и `Options` под одним корнем средства выбора, в том числе когда параметры находятся на другой странице раскрывающегося списка. Дочерние элементы корня в виде функции рендеринга предоставляют `value`, `selectedCurrency` и `disabled` для меток и вспомогательного содержимого, управляемых вызывающей стороной.

```tsx theme={null}
import { CurrencyPicker } from 'twenty-ui/components/input';
import { Dropdown } from 'twenty-ui/components/navigation';

const CURRENCIES = [
  { code: 'EUR', name: 'Euro' },
  { code: 'USD', name: 'US Dollar' },
];

export const ComposedCurrency = () => (
  <Dropdown.Root type="picker">
    <CurrencyPicker.Root
      currencies={CURRENCIES}
      defaultValue="USD"
      closeOnSelect={false}
    >
      {({ value }) => (
        <>
          <CurrencyPicker.Trigger
            aria-label={`Invoice currency: ${value ?? 'none'}`}
            placeholder="Choose a currency"
          />
          <Dropdown.Content aria-label="Invoice currency" width={280}>
            <Dropdown.Title>Invoice currency</Dropdown.Title>
            <CurrencyPicker.Options
              searchLabel="Search currencies"
              emptyLabel="No currencies found"
            />
          </Dropdown.Content>
        </>
      )}
    </CurrencyPicker.Root>
  </Dropdown.Root>
);
```

Dropdown управляет открытием, размещением всплывающего окна, страницами, навигацией поиска и фокусом. Средство выбора использует группу выбора Dropdown для сохранения выбранных значений и политики закрытия. `Root.closeOnSelect` по умолчанию имеет значение `true`; используйте `false`, чтобы оставить всплывающее окно открытым после выбора валюты. Клавиши со стрелками, Home и End перемещают фокус без изменения значения. Enter, Space или активация указателем выбирают включённый параметр. Отключённые валюты остаются видимыми, и их нельзя выбрать.

## Поиск и сортировка

Поиск по параметрам включён по умолчанию. Поиск игнорирует окружающие пробелы и без учёта регистра сопоставляет коды, названия, символы и метку по умолчанию `Name (CODE)`, используя одинаковые правила для всех локалей браузера. `getSearchText` в корне заменяет текст, доступный для поиска, для каждой валюты. Настройка отображения и текст поиска независимы друг от друга.

Результаты сохраняют порядок каталога. Установите `selectedFirst` для сокращённого варианта или корня, чтобы переместить выбранную валюту перед остальными совпадениями. Запрос, исключающий её, также удаляет её строку. Неизвестное значение не создаёт выбранный результат. Пустые результаты отображают `emptyLabel` в области состояния.

Установите `Options.searchable={false}`, чтобы не отображать поле поиска. `Options.searchProps` нацелен на нативное поле ввода поиска, включая его `ref`, `render`, доступные атрибуты и контролируемое `value` или неконтролируемое `defaultValue`. `searchProps.onValueChange` получает запрос. При использовании сокращённого варианта передавайте эти параметры через `optionsProps`.

Поле поиска получает фокус при открытии средства выбора с возможностью поиска. Enter при непустом запросе активирует первый включённый результат. При пустом запросе перед выбором переместите фокус на параметр. Активация поиска во время составления IME и новый поиск при повторном открытии по-прежнему подчиняются общим контрактам поиска Dropdown и сеанса страницы.

## Представление и нативные цели

По умолчанию триггер показывает выбранный код. `renderValue` получает `{ value, selectedCurrency, disabled }` для настройки этого отображения без повторного поиска валюты. `Trigger.children` переопределяет отображение значения, а `Trigger.placeholder` задаёт пустое отображение. `getOptionLabel` настраивает содержимое каждого параметра с меткой по умолчанию `Name (CODE)`. Названия валют, символы, метки и содержимое параметров определяются вызывающей стороной.

Нативные атрибуты кнопки сокращённого варианта, обработчики событий, `className`, `style`, `ref` и `render` нацелены на его триггер. `triggerProps` настраивает эту же кнопку. Используйте `optionsProps` для обёртки div параметров и его вложенный `searchProps` для поля ввода. `contentProps` настраивает всплывающее окно Dropdown. `open`, `defaultOpen` и `onOpenChange` координируют открытое состояние сокращённого варианта.

При составном использовании нативные атрибуты, `ref` и `render` в `Trigger` нацелены на его кнопку, а в `Options` — на его обёртку div. `Options.listLabel` задаёт имя только внутреннему списку выбора. Передавайте предоставленные props и ref из пользовательского компонента `render`. Стилизация обёртки не изменяет нативную цель поля ввода.

Установите `disabled` для сокращённого варианта или корня, чтобы отключить открытие, поиск и выбор. Свойство `disabled` части может дополнительно отключить эту часть. Выбор является значением средства выбора; нативная отправка формы, сброс, обязательная проверка и интеграция с Field остаются вне этого API.

## Метки и интеграция с приложением

`searchLabel` по умолчанию имеет значение `Search` и задаёт заполнитель поиска и доступное имя. `emptyLabel` по умолчанию имеет значение `No results` и принимает содержимое. Предоставьте из приложения локализованные исходные метки, доступное имя триггера и любой заполнитель. Содержимое Dropdown получает имя триггера, если только его не задаёт `Dropdown.Title` или явная метка содержимого. Список выбора по умолчанию получает зарегистрированный заголовок Dropdown или имя триггера. Установите `Options.listLabel`, чтобы дать только этому списку собственное доступное имя, или передайте `optionsProps.listLabel` при использовании сокращённого варианта. Нативные `aria-label` и `aria-labelledby` в `Options` задают метку только для его обёртки. Триггер сохраняет собственное доступное имя.

Приложение управляет редактированием суммы, хранением валюты, форматированием, загрузкой каталога и его начальным значением. Адаптер должен сопоставлять сохранённые коды валют и поведение очистки с `value` и `onValueChange`, сохраняя правила форматирования и резервных значений приложения. Храните переведённые названия валют и метки в приложении.

## Рендерер Front-компонента

Тестовые сценарии песочницы React и Preact охватывают сокращённый и составной поиск и выбор, отключённые элементы управления и параметры, ссылки на триггеры, очистку с null, внешние контролируемые обновления, повторное открытие и восстановление фокуса по Escape. Они также проверяют, что очистка предыдущего запроса и ввод `$` сохраняют запрос по символу.

Видимость всплывающего окна, геометрия, прокрутка и закрытие зависят от поддержки Dropdown и портала общим средством рендеринга. Средство выбора использует эту общую реализацию.

## Свойства

**children** `ReactNode`

Caller-owned trigger content that overrides the selected value display.

**className** `string | ((state: PopoverTriggerState) =\> string | undefined)`

Class applied to the trigger button.

**closeOnSelect** `boolean`

Whether committing an enabled option closes the dropdown. Defaults to true. A canceled selection never closes automatically.

**contentProps** `Omit\<DropdownContentProps, "children"\>`

Dropdown popup props, including placement, width, and accessible attributes.

**currencies** `readonly CurrencyPickerOption[]` *required*

Available currencies in display order. Each code is a unique stable identifier; name and optional symbol are caller-owned data. A currency can be disabled.

**defaultOpen** `boolean`

Whether the popup is initially open when uncontrolled.

**defaultValue** `string | null` (default: null)

Initial uncontrolled currency code, or null for an empty selection. Defaults to null.

**disabled** `boolean` (default: false)

Disables opening, search, and every currency option.

**getOptionLabel** `((currency: CurrencyPickerOption) =\> ReactNode)` (default: Name (CODE))

Returns caller-owned content for a currency option. Defaults to Name (CODE). Display content does not change the search text.

**getSearchText** `((currency: CurrencyPickerOption) =\> string)` (default: Name (CODE) and symbol)

Returns searchable text for a currency. Defaults to Name (CODE) and its optional symbol. Search trims the query and matches without case sensitivity.

**id** `string`

ID forwarded to the trigger button.

**nativeButton** `boolean` (default: true)

Whether render composes a native button. Set false for a custom non-button element so Base UI supplies button interaction.

**onEscapeKeyDown** `((event: DropdownDismissEvent) =\> void)`

Called before Escape closes the popup. Call event.preventDefault() to keep it open.

**onInteractOutside** `((event: DropdownDismissEvent) =\> void)`

Called before an outside press or Tab out closes the popup. Call event.preventDefault() to keep it open.

**onOpenChange** `((open: boolean) =\> void)`

Called with the next open state when the popup opens or closes.

**onValueChange** `((value: string | null, eventDetails: DropdownSelectionGroupChangeEventDetails) =\> void)`

Called with the next code or null and cancellable Dropdown selection details: event, reason, trigger, cancel and isCanceled. Calling cancel() preserves selection and prevents automatic close. Repeated single selection does not emit a change.

**open** `boolean`

Whether the popup is open. Use with onOpenChange to control it.

**optionsProps** `CurrencyPickerOptionsProps`

Props for the options wrapper div, listLabel, and search behavior. Native input customization belongs in optionsProps.searchProps.

**placeholder** `ReactNode`

Trigger content displayed when the selected value is null.

**ref** `Ref\<HTMLButtonElement\>`

Ref to the trigger button, or the element composed through render.

**render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, PopoverTriggerState\>`

Replaces the native trigger button. Forward the supplied props and ref when rendering a custom component.

**renderValue** `((state: CurrencyPickerState) =\> ReactNode)`

Returns selected trigger content from \{ value, selectedCurrency, disabled }. The default display is the raw code, or the trigger placeholder when null. Trigger children override it.

**selectedFirst** `boolean` (default: false)

Moves the matching selected currency before other results. Defaults to false, preserving catalogue order.

**style** `CSSProperties | ((state: PopoverTriggerState) =\> CSSProperties | undefined)`

Inline styles applied to the trigger button.

**triggerProps** `CurrencyPickerTriggerProps`

Props for the trigger button, including native attributes, ref, render, placeholder, and caller-owned children. These override shorthand trigger props.

**value** `string | null`

Controlled currency code or null for an empty selection. Undefined leaves selection uncontrolled. Empty and unknown strings remain identifiers.

### CurrencyPicker.Root

**Root.children** `ReactNode | ((state: CurrencyPickerState) =\> ReactNode)` *required*

Picker parts and supporting content, or a render function receiving \{ value, selectedCurrency, disabled }. Root owns selection and prepared data without adding a DOM element.

**Root.closeOnSelect** `boolean`

Whether committing an enabled option closes the dropdown. Defaults to true. A canceled selection never closes automatically.

**Root.currencies** `readonly CurrencyPickerOption[]` *required*

Available currencies in display order. Each code is a unique stable identifier; name and optional symbol are caller-owned data. A currency can be disabled.

**Root.defaultValue** `string | null` (default: null)

Initial uncontrolled currency code, or null for an empty selection. Defaults to null.

**Root.disabled** `boolean` (default: false)

Disables the trigger, search input, and every currency option.

**Root.getOptionLabel** `((currency: CurrencyPickerOption) =\> ReactNode)` (default: Name (CODE))

Returns caller-owned content for a currency option. Defaults to Name (CODE). Display content does not change the search text.

**Root.getSearchText** `((currency: CurrencyPickerOption) =\> string)` (default: Name (CODE) and symbol)

Returns searchable text for a currency. Defaults to Name (CODE) and its optional symbol. Search trims the query and matches without case sensitivity.

**Root.onValueChange** `((value: string | null, eventDetails: DropdownSelectionGroupChangeEventDetails) =\> void)`

Called with the next code or null and cancellable Dropdown selection details: event, reason, trigger, cancel and isCanceled. Calling cancel() preserves selection and prevents automatic close. Repeated single selection does not emit a change.

**Root.renderValue** `((state: CurrencyPickerState) =\> ReactNode)`

Returns selected trigger content from \{ value, selectedCurrency, disabled }. The default display is the raw code, or the trigger placeholder when null. Trigger children override it.

**Root.selectedFirst** `boolean` (default: false)

Moves the matching selected currency before other results. Defaults to false, preserving catalogue order.

**Root.value** `string | null`

Controlled currency code or null for an empty selection. Undefined leaves selection uncontrolled. Empty and unknown strings remain identifiers.

### CurrencyPicker.Trigger

**Trigger.children** `ReactNode`

Caller-owned trigger content that overrides the selected value display.

**Trigger.className** `string | ((state: PopoverTriggerState) =\> string | undefined)`

Class applied to the trigger button.

**Trigger.disabled** `boolean` (default: false)

Additionally disables the native trigger button. Root disabled state always takes precedence.

**Trigger.id** `string`

ID forwarded to the trigger button.

**Trigger.nativeButton** `boolean` (default: true)

Whether render composes a native button. Set false for a custom non-button element so Base UI supplies button interaction.

**Trigger.placeholder** `ReactNode`

Trigger content displayed when the selected value is null.

**Trigger.ref** `Ref\<HTMLButtonElement\>`

Ref to the trigger button, or the element composed through render.

**Trigger.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, PopoverTriggerState\>`

Replaces the native trigger button. Forward the supplied props and ref when rendering a custom component.

**Trigger.style** `CSSProperties | ((state: PopoverTriggerState) =\> CSSProperties | undefined)`

Inline styles applied to the trigger button.

### CurrencyPicker.Options

**Options.className** `string`

Class applied to the options wrapper div.

**Options.disabled** `boolean` (default: false)

Additionally disables search and every currency option. Root disabled state always takes precedence.

**Options.emptyLabel** `ReactNode` (default: No results)

Content announced when no currencies match. Defaults to No results.

**Options.listLabel** `string`

Accessible name for the selection listbox. Defaults to the registered Dropdown title or trigger name. Native accessible attributes on Options target only its wrapper.

**Options.ref** `Ref\<HTMLDivElement\>`

Ref to the options wrapper div, or the element composed through render.

**Options.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, \{\}\>`

Replaces the non-interactive wrapper div. Forward the supplied props and ref when rendering a custom component. Use searchProps.render to customize the input.

**Options.searchable** `boolean` (default: true)

Renders a search input above the options. Defaults to true.

**Options.searchLabel** `string` (default: Search)

Search placeholder and accessible name. Defaults to Search.

**Options.searchProps** `DropdownSearchProps`

Native input attributes, ref, render, and controlled or uncontrolled query props forwarded to Dropdown.Search. Use value with onValueChange or defaultValue.

**Options.style** `CSSProperties`

Inline styles applied to the options wrapper div.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.