I'm trying to add an event listener for keydown event in an image (or div) tag. It works if I add it to the document with document.addEventListener, but it doesn't when I try to put it into the specific element that I create in react (I noted in the code what works and what doesn't). Also handleClick works and handleKey does not, no matter which format I put it into the tag with.
class PrescriptionImage extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
patient: "",
rotation: 0
};
this.handleKey = this.handleKey.bind(this);
}
handleClick() {
this.setState({rotation: this.state.rotation + 270})
}
handleKey(e) {
e.preventDefault();
console.log(e);
if (e.code == 'ArrowLeft') {
if (e.ctrlKey) {
this.setState({rotation: this.state.rotation + 270})
}
}
}
componentDidMount() {
// document.getElementById("left").addEventListener("keydown", this.handleKey, true); This doesn't work (no error)
// this.RxImage.addEventListener("keydown", this.handleKey, false); This doesn't work, (can't find addEventListener of "undefined")
// document.addEventListener("keydown", this.handleKey, false); This works.
fetch("http://localhost:3333/patientAddress.json")
.then(res => res.json())
.then(
result => {
this.setState({
isLoaded: true,
patient: result.order.patient
});
},
error => {
this.setState({
isLoaded: true,
error
});
}
);
}
componentWillUnmount(){
document.removeEventListener("keydown", this.handleKey, false);
}
render() {
const { error, isLoaded, patient, rotation } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return <img className="prescription-image" style={{width: "98%", height: "98%", transform: `rotate(${rotation}deg)`}} src={"data:image/png;base64," + patient.rx.imageData} onClick={() => this.handleClick()} onKeyDown={this.handleKey} />;
}
}
}
ReactDOM.render(<PrescriptionImage />, document.getElementById("left"));
onKeyDown(camelcase). Try renaming your prop: reactjs.org/docs/events.html#keyboard-events