-
Notifications
You must be signed in to change notification settings - Fork 94
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
docs(Combobox): add example: opening by focus (#3727)
closes #3724
- Loading branch information
Showing
2 changed files
with
125 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
61 changes: 61 additions & 0 deletions
61
...nts/Combobox/__stand__/examples/ComboboxExampleOpenByFocus/ComboboxExampleOpenByFocus.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
import { Example } from '@consta/stand'; | ||
import React, { useEffect, useRef, useState } from 'react'; | ||
|
||
import { Button } from '##/components/Button'; | ||
import { Combobox } from '##/components/Combobox'; | ||
import { useFlag } from '##/hooks/useFlag'; | ||
|
||
type Item = { | ||
label: string; | ||
id: number; | ||
}; | ||
|
||
const items: Item[] = [ | ||
{ | ||
label: 'Первый', | ||
id: 1, | ||
}, | ||
{ | ||
label: 'Второй', | ||
id: 2, | ||
}, | ||
{ | ||
label: 'Третий', | ||
id: 3, | ||
}, | ||
]; | ||
|
||
export function ComboboxExampleOpenByFocus() { | ||
const [value, setValue] = useState<Item | null>(); | ||
const [isOpened, setIsOpened] = useFlag(); | ||
const inputRef = useRef<HTMLInputElement>(null); | ||
|
||
const handleFocus = () => { | ||
inputRef.current?.focus(); | ||
}; | ||
|
||
// Запрещаем всплытие клика c input, чтобы предотвратить рассинхронизацию isOpened | ||
// с внутренним состоянием раскрытия списка. Так как клик по компоненту переключает состояние скрыт/раскрыт, | ||
// нам при фокусе требуется не переключение (toggle), а включение (setTrue) | ||
useEffect(() => { | ||
if (inputRef.current) { | ||
inputRef.current.onclick = (e) => e.stopPropagation(); | ||
} | ||
}, [inputRef.current]); | ||
|
||
return ( | ||
<Example col={1}> | ||
<Button onClick={handleFocus} label="Эмулировать фокус на элемент" /> | ||
<Combobox | ||
inputRef={inputRef} | ||
items={items} | ||
value={value} | ||
onChange={setValue} | ||
placeholder="Выберите элемент" | ||
dropdownOpen={isOpened} | ||
onDropdownOpen={setIsOpened.set} | ||
onFocus={setIsOpened.on} | ||
/> | ||
</Example> | ||
); | ||
} |