Skip to content

Commit da9270d

Browse files
authored
Merge pull request #1800 from dxc-technology/Mil4n0r/number_input_scroll-fix
Handle scroll in Number Inputs
2 parents 3ac400c + 74f4d39 commit da9270d

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

lib/src/text-input/TextInput.tsx

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { useContext, useEffect, useRef, useState } from "react";
1+
import React, { useCallback, useContext, useEffect, useRef, useState } from "react";
22
import styled, { ThemeProvider } from "styled-components";
33
import useTheme from "../useTheme";
44
import useTranslatedLabels from "../useTranslatedLabels";
@@ -246,6 +246,12 @@ const DxcTextInput = React.forwardRef<RefType, TextInputPropsType>(
246246
break;
247247
}
248248
};
249+
const handleWheel = useCallback((event: WheelEvent) => {
250+
if (document.activeElement === inputRef.current) {
251+
event.preventDefault();
252+
event.deltaY < 0 ? incrementNumber(inputRef.current.value) : decrementNumber(inputRef.current.value);
253+
}
254+
}, []);
249255

250256
const handleClearActionOnClick = () => {
251257
changeValue("");
@@ -268,8 +274,7 @@ const DxcTextInput = React.forwardRef<RefType, TextInputPropsType>(
268274
inputRef?.current?.setAttribute("step", step);
269275
inputRef?.current?.setAttribute("type", type);
270276
};
271-
const decrementNumber = () => {
272-
const currentValue = value ?? innerValue;
277+
const decrementNumber = (currentValue = value ?? innerValue) => {
273278
const numberValue = Number(currentValue);
274279
const steppedValue = Math.round((numberValue - numberInputContext?.stepNumber + Number.EPSILON) * 100) / 100;
275280

@@ -285,8 +290,7 @@ const DxcTextInput = React.forwardRef<RefType, TextInputPropsType>(
285290
else changeValue(-numberInputContext.stepNumber);
286291
}
287292
};
288-
const incrementNumber = () => {
289-
const currentValue = value ?? innerValue;
293+
const incrementNumber = (currentValue = value ?? innerValue) => {
290294
const numberValue = Number(currentValue);
291295
const steppedValue = Math.round((numberValue + numberInputContext?.stepNumber + Number.EPSILON) * 100) / 100;
292296

@@ -342,6 +346,16 @@ const DxcTextInput = React.forwardRef<RefType, TextInputPropsType>(
342346
);
343347
}, [value, innerValue, suggestions, numberInputContext]);
344348

349+
useEffect(() => {
350+
const input = inputRef.current;
351+
352+
input.addEventListener('wheel', handleWheel, { passive: false });
353+
354+
return () => {
355+
input.removeEventListener('wheel', handleWheel);
356+
};
357+
}, [handleWheel]);
358+
345359
return (
346360
<ThemeProvider theme={colorsTheme.textInput}>
347361
<TextInputContainer margin={margin} size={size} ref={ref}>

0 commit comments

Comments
 (0)