Skip to content

Commit e6f46a3

Browse files
authored
fix(Range): ticks fix (#438)
* Add component arguments * Add default values for displayTicks and ticksStep * Fix number of ticks calculation * Condition displaying ticks on the displayTicks logic * Fix problem with negative step sizes * Remove usage of useMemo
1 parent 13c8db2 commit e6f46a3

1 file changed

Lines changed: 12 additions & 9 deletions

File tree

src/Range/Range.tsx

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,12 @@ export type RangeProps = Omit<
1515
IComponentBaseProps & {
1616
color?: ComponentColor
1717
size?: ComponentSize
18+
displayTicks?: boolean
19+
ticksStep: number
1820
}
1921

2022
const Range = forwardRef<HTMLInputElement, RangeProps>(
21-
({ color, size, step, dataTheme, className, ...props }, ref): JSX.Element => {
23+
({ color, size, step, displayTicks, ticksStep, dataTheme, className, ...props }, ref): JSX.Element => {
2224
const classes = twMerge(
2325
'range',
2426
className,
@@ -37,13 +39,14 @@ const Range = forwardRef<HTMLInputElement, RangeProps>(
3739
})
3840
)
3941

40-
const isNumeric = (n: any): n is number =>
41-
!isNaN(parseFloat(n)) && isFinite(n)
42+
const calculatedDisplayTicks = displayTicks ?? (step !== undefined);
43+
const calculatedStep = step !== undefined ? Number(step) : 1; // default value per HTML standard
44+
const calculatedTicksStep = ticksStep ?? calculatedStep;
45+
const min = props.min !== undefined ? Number(props.min) : 0; // default value per HTML standard
46+
const max = props.max !== undefined ? Number(props.max) : 100; // default value per HTML standard
4247

43-
const numSteps = useMemo(() => {
44-
const safeStep = Math.max(1, Number(step))
45-
return Math.ceil(100 / safeStep) ?? 1
46-
}, [props.max, step])
48+
// use Math.max to solve multiple issues with negative numbers throwing errors
49+
const numTicks = Math.max(Math.ceil((max - min) / calculatedTicksStep), 1) + 1;
4750

4851
return (
4952
<>
@@ -55,9 +58,9 @@ const Range = forwardRef<HTMLInputElement, RangeProps>(
5558
data-theme={dataTheme}
5659
className={classes}
5760
/>
58-
{isNumeric(step) && (
61+
{calculatedDisplayTicks && (
5962
<div className="w-full flex justify-between text-xs px-2">
60-
{[...Array(numSteps + 1)].map((_, i) => {
63+
{[...Array(numTicks)].map((_, i) => {
6164
return <span key={i}>|</span>
6265
})}
6366
</div>

0 commit comments

Comments
 (0)