Skip to content

Commit

Permalink
Merge pull request #2234 from webb-tools/linh/fix-input
Browse files Browse the repository at this point in the history
Fix cursor moves to the end when changing value in input
  • Loading branch information
drewstone authored Apr 15, 2024
2 parents e7ac878 + acc4066 commit 762b53e
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions libs/webb-ui-components/src/components/Input/Input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export const Input: React.FC<InputProps> = (props) => {
...restProps
} = props;
const [value, setValue] = useState(initialValue);
const [cursor, setCursor] = useState<number | null>(null);

useEffect(() => {
setValue(initialValue);
Expand All @@ -77,6 +78,10 @@ export const Input: React.FC<InputProps> = (props) => {
return () => clearTimeout(timeout);
}, [debounceTime, onChange, value]);

useEffect(() => {
inputRef?.current?.setSelectionRange(cursor, cursor);
}, [inputRef, cursor, value]);

// Override the size of left icon prop to 'md'
const leftIcon = useMemo(() => {
if (!leftIconProp) {
Expand Down Expand Up @@ -200,11 +205,12 @@ export const Input: React.FC<InputProps> = (props) => {
required={isRequired}
className={mergedInputClsx}
value={value}
onChange={(eve) =>
onChange={(e) => {
setCursor(e.target.selectionStart);
isControlled && onChange !== undefined
? onChange(eve.target.value)
: setValue(eve.target.value)
}
? onChange(e.target.value)
: setValue(e.target.value);
}}
{...restProps}
/>

Expand Down

0 comments on commit 762b53e

Please sign in to comment.