React - Select multiple checkboxes holding Shift key

Viewed 2833

I have a list of checkboxes in my React App. When I hold Shift key and click one - the others between current and the nearest checked one should become selected.

For now I'm tring to do somethimg like this:

<input onChange={(e)=>this.handleCheckbox(e)} value={id} checked={this.state.selected.IndexOf(id) > -1} type="checkbox" />

handleCheckbox(e){
  if(e.shiftKey){
    console.log("shiftKey is hold")
  }
  //here goes some logic to save checkboxes in the state
}

But the condition if(e.shiftKey) is never executed. What am I doing wrong?

2 Answers

For future visitors:

To check if the Shift key is pressed, check the e.nativeEvent.shiftKey in the click event.

You still have to implement the logic for actually checking the boxes. If you need help with that, let me know.

Hope this helps.

onChange is trigged after you let the key up. You should use the onKeyDown event.

Related