Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
How to display keystroke on page using react

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!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Instead of

 this.state.count = event.keyCode;

you need to use

this.setState({count: event.keyCode})
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!