Preact: how to get e.keycode or e.which from event

Created on 1 Dec 2016  路  3Comments  路  Source: preactjs/preact

how to get e.keycode or e.which from event (tried using preact | preact + preact-compat)

import { h, Component } from 'preact';

export default class Comp extends Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
    }

        handleChange(e) {
        console.log(e.which);   // undefined
       }
    render() {
        return (
            <input type="text" onInput={this.handleChange}/>
        );
    }
}

/*
event object contains
Event {
   bubbles: true
   cancelBubble:false
   cancelable:false
   composed:false
   currentTarget:null
   defaultPrevented:false
   eventPhase:0
   isTrusted:true
   path:Array[13]
   returnValue:true
   srcElement:input
   target:input
   timeStamp:5857.87
   type:"change"
   __proto__:Event
}
/*


question

All 3 comments

Hi @nopantsmonkey! If you need to respond to keyboard input specifically, you'll want to use the onkey* handlers:

import { h, Component } from 'preact';

export default class Comp extends Component {
    constructor(props) {
        super(props);
        this.handleKeyDown = this.handleKeyDown.bind(this);
    }

        handleKeyDown(e) {
        console.log(e.which);   // the key code
       }
    render() {
        return (
            <input type="text" onKeyDown={this.handleChange} />
        );
    }
}

Let me know if that answers your question and we can close this issue out :)

Thank You. Closing the issue

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jasongerbes picture jasongerbes  路  3Comments

KnisterPeter picture KnisterPeter  路  3Comments

matthewmueller picture matthewmueller  路  3Comments

noise-machines picture noise-machines  路  3Comments

jescalan picture jescalan  路  3Comments