From 7161c35516c3890d3533d0ebf9211fff4a67a5bd Mon Sep 17 00:00:00 2001 From: Alexander Yatsenko Date: Fri, 8 Nov 2024 15:32:52 +0300 Subject: [PATCH] fix(input): set caret position at the end of the input programmatically (#1413) * fix(input): set caret position at the end of the input programmatically * Create tame-masks-pump.md --- .changeset/tame-masks-pump.md | 5 +++++ .../input/src/components/base-input/Component.tsx | 13 ++++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 .changeset/tame-masks-pump.md diff --git a/.changeset/tame-masks-pump.md b/.changeset/tame-masks-pump.md new file mode 100644 index 0000000000..ed5f384fef --- /dev/null +++ b/.changeset/tame-masks-pump.md @@ -0,0 +1,5 @@ +--- +"@alfalab/core-components-input": patch +--- + +Исправлен баг с автофокусом и SSR. Каретка при автофокусе теперь программно устанавливается в конец ввода. diff --git a/packages/input/src/components/base-input/Component.tsx b/packages/input/src/components/base-input/Component.tsx index 200aac1e3a..23e243dd8d 100644 --- a/packages/input/src/components/base-input/Component.tsx +++ b/packages/input/src/components/base-input/Component.tsx @@ -18,7 +18,7 @@ import cn from 'classnames'; import { FormControlProps } from '@alfalab/core-components-form-control'; import { getDataTestId } from '@alfalab/core-components-shared'; import { StatusBadge } from '@alfalab/core-components-status-badge'; -import { useFocus } from '@alfalab/hooks'; +import { useFocus, useLayoutEffect_SAFE_FOR_SSR } from '@alfalab/hooks'; import { ClearButton } from '../clear-button'; @@ -283,6 +283,17 @@ export const BaseInput = React.forwardRef( const clearButtonVisible = clear && filled && !disabled && !readOnlyProp; const hasInnerLabel = label && labelView === 'inner'; + useLayoutEffect_SAFE_FOR_SSR(() => { + // https://github.com/facebook/react/issues/14125 + if (restProps.autoFocus) { + const input = inputRef.current; + + if (input) { + input.setSelectionRange(input.value.length, input.value.length); + } + } + }, []); + const handleInputFocus = useCallback( (event: React.FocusEvent) => { if (!readOnlyProp || disableUserInput) {