0

I have a playlist that I'm trying to bind a keyDown to.. the problem is that I cannot use a typical React.Component as I am using a library (https://github.com/clauderic/react-sortable-hoc) that requires me to use a functional Stateless Component (SortableContainer). So I have no way to access props or a state even. I've tried to pass data as a parameter with nothing working..

This works, but I need to pass data to handleKeyDown somehow.. in particular I really want to pass "props" into handleKeyDown somehow

function handleKeyDown(e) {
  // **** I need some way to access outside data in here some how..
  //      whether it's passed as a parameter or any other way
  console.log(e.keyCode);
}

const PlaylistPages = SortableContainer(( props ) => {
  return (
    <div className="playlist-sortable" onKeyDown={handleKeyDown} tabIndex="0">
    // etc
  );
}
user1189352
  • 3,628
  • 12
  • 50
  • 90

3 Answers3

6

Use arrow function, and pass the props and event object inside handleKeyDown function.

Write it like this:

onKeyDown = { e => handleKeyDown(props, e)}

handleKeyDown(props, e){
   console.log(e.target, props);
}
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
1

I think better way of writing would be:

onClick={clickHandler(passedData)}

clickHandler= (passedData) => (e) => {
  console.log(e)
  console.log(passedData)
}

Arrow functions would cause unnecessary re-renders.

tarzen chugh
  • 10,561
  • 4
  • 20
  • 30
  • Could you clarify a bit more about this solution? it does work, but it's not straight forward to understand this behavior. – sergioviniciuss Sep 27 '19 at 08:15
  • 1
    It is infact curry function. Take a look at [this](https://stackoverflow.com/a/32787782/7845230) link for better clarification. – tarzen chugh Sep 27 '19 at 09:01
-1

You can pass your parameters to a higher order function which will do the trick for you

function handleKeyDown(passedData) {
    return e => {
        console.log(passedData); // hello
        console.log(e.keyCode);
    }
}

const PlaylistPages = SortableContainer(( props ) => {
  const dataToPass = 'hello'
  return (
    <div className="playlist-sortable" onKeyDown={handleKeyDown(dataToPass)} tabIndex="0">
    // etc
  );
}
Honza
  • 683
  • 7
  • 22