Reputation: 3885
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
);
}
Upvotes: 0
Views: 2764
Reputation: 11257
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.
Upvotes: 1
Reputation: 104379
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);
}
Upvotes: 6
Reputation: 703
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
);
}
Upvotes: -1