My file is as follows.
import React, {Component} from 'react';
import './App.css';
class App extends Component {
constructor(props){
super(props);
this.state = {
count: 0
};
}
onKeyPress(event){
console.log(event.keyCode);
this.state.count = event.keyCode;
}
componentDidMount(){
document.addEventListener("keydown", this.onKeyPress, false);
}
componentWillUnmount(){
document.removeEventListener("keydown", this.onKeyPress, false);
}
render() {
return (
<div className="App">
<header className="App-header">
<p>
{this.state.count}
</p>
</header>
</div>
);
}
}
export default App;
I can correctly log the keystrokes in the console, but once I added this.state.count = event.keyCode;
I am getting the error TypeError: Cannot set properties of undefined (setting 'count')
Not sure what the proper solution is, any help would be appreciated!
CodePudding user response:
Instead of
this.state.count = event.keyCode;
you need to use
this.setState({count: event.keyCode})
CodePudding user response:
Add :
this.setState({
count: event.keyCode
})
Or, with hooks :
import React, {useState, useEffect} from "react";
import "./style.css";
export default function App() {
const [count, setCount] = useState(0)
const onKeyPress = (event) => {
console.log(event.keyCode)
setCount(event.keyCode)
}
useEffect(() => {
document.addEventListener('keydown', onKeyPress);
return () => {
document.removeEventListener('keydown', onKeyPress);
};
}, [])
return (
<div className="App">
<header className="App-header">
<p>{count}</p>
</header>
</div>
);
}
Demo : Stackblitz
CodePudding user response:
Take a look at https://keycode.info for an example of capturing event keys.
You should look into upgrading to Function Components (React 17 ). The example below covers the use of hooks in React 17.
const { useCallback, useEffect, useMemo, useState } = React;
const App = () => {
const [key, setKey] = useState(0);
const [keyCode, setKeyCode] = useState(0);
useEffect(() => {
document.addEventListener('keydown', onKeyPress, false);
return () => {
document.removeEventListener('keydown', onKeyPress, false);
};
}, []);
const onKeyPress = useCallback(({
key: newKey,
keyCode: newKeyCode,
preventDefault
}) => {
setKey(newKey);
setKeyCode(newKeyCode);
preventDefault();
}, []);
return useMemo(() => (
<div className="App">
<header>
<p><label className="field">Key</label>{key}</p>
<p><label className="field">KeyCode</label>{keyCode}</p>
</header>
</div>
), [key, keyCode]);
};
ReactDOM.render(<App />, document.getElementById('react'));
.field { font-weight: bold; }
.field::after { content: ': '; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>