2

I'm using for my project the Range component from here: https://www.npmjs.com/package/rc-slider

There are 4 values marked on the range:

  • the min value,
  • a (let's say) random value in the middle,
  • themax value
  • the currentlyChosenValue.

The requirement was to introduce steps for this slider, so that

  1. the user only sees values rounded to the nearest 10 as currentlyChosenValue, when he is dragging the slider,
  2. the user only sees values rounded up to the nearest 10, when he pushes the left-right arrow keys.

I could not use the step property defined for the , as my min, max and middle values are pretty random (they are not rounded). Therefore, I defined a function which rounds the values onChange - it works properly for point #1 (e.g. rounding to min, when selected value is close to min).

However, when the user presses the left/right arrow key, the slider tries to move one step left/right - which gets rounded back to the original value ==> slider won't move eventually. I could not find a way to define a separate onKeyDown event for my Range, I tried to add a Handle with an onKeyDown - but my function there was never triggered.

  import { Handle, Range } from "rc-slider";

  const handle = props => {
    const { value, ...restProps } = props;
    const change = event => {
      // was never triggered
      console.log("a key was pressed", event);
    };
    return <Handle value={value} onKeyPress={change} {...restProps} />;
  };

  <Range
    handle={handle}
    value={[min, middle, currentlyChosenValue]}
    min={min}
    max={max}
    onChange={memoizedOnChange}
  />
axel
  • 3,778
  • 4
  • 45
  • 72
Antona
  • 107
  • 2
  • 14

2 Answers2

2

Since <Handle/> is a component, you're passing onKeyPress={change} down as a prop.

You could wrap a div around <Handle/> and put onKeyPress={change} on that div.

Your also want to use tabIndex="0" as an attribute when you do this. This link talks about why:

onKeyDown event not working on divs in React

return (
    <div onKeyPress={change} tabIndex="0">
        <Handle value={value} {...restProps} />;
    </div>
)
Eric Jones
  • 86
  • 8
  • Thanks for the comment, I've tried it out, and I'm not sure, why, but the change function still doesn't get triggered.. :( Besides, I get some eslint errors, if I add an Event Handler to a `div` - therefore, I'm not sure, if this would pass our code review (we also have to comply with the WCAG requirements and I suspect that this might be against it) – Antona Aug 14 '19 at 16:38
0

You can wrap a div around the Range component and listen for key events there.