I am facing an issue and don't understand why my code doesn't work.
The point :
- I have a series of buttons, each one representing keyboard keys, and the content of each button is the keyboard key "value" (A, B, C, D,…)
- I have a SFC named Key.js which creates a button with a given letter associated (done in an external component function)
- In the render() function of App.js, I map LETTERS (an array containing all letters from A to Z) to create the button list
- When I click on one button, I want to get the letter associated with it (this I had done) but also get the HTML button element clicked (to check for specific attributes etc…). This is the problem
Here is the code for Key.js :
const Key = ({ letter, onClick }) => (
<button className={`keyboardLetter`} onClick={() => onClick(letter)} >{ letter }</button>
);
export default Key;
Here is the code rendering it in App.js :
render() {
return (
<div className="keyboard">
{
// LETTERS is an array containing letters from A to Z
LETTERS.map((letter, index) => (
<Key letter={letter} onClick={this.handleKeyClick} key={index} />
))
}
</div>
)
}
Here is the code for the handleKeyClick method :
// Arrow function for binding
handleKeyClick = (letter) => {
// Here I do several operations for my app to work (setState() etc…)
// I can get the letter I clicked by doing :
console.log(letter);
// The point is I can not retrieve the HTML button element clicked, even with :
console.log(letter.target) // returns undefined
// letter.currentTarget, .parentElement or .parentNode also return undefined
};
I have found a workaround, but if I understood correctly is not the best practice to do. It is changing the onClick event on Key.js SFC to this :
onClick={(event) => onClick(letter, event)}
And then use the event property like so in my method :
handleKeyClick = (letter, event) => { }
With this I can get the button element clicked with event.target, but if I understood correctly would cause less performances and seems more trouble and code to get my App working as wanted.
- I don't understand why my binding with the arrow function on handleKeyClick doesn't let me get to the HTML element clicked ?
Thank you very much for your time and help.
Tom