2

I have an input element with the onKeyPress property on it.

<input type="text" onKeyPress={this.keyPressed}

I want to know when Enter or Escape is pressed and act accordingly.

keyPressed: function(e) {

    if (e.key == 'Enter') {
        console.log('Enter was pressed!');
    } 
    else if (e.key == 'Escape') {
        console.log('Escape was pressed!');
    } 
    else {
        return;
    }
}

I am able to detect when Enter is pressed but NOT when Escape is.


EDIT

  • e.charCode == 27 ( Not working )
  • e.keyCode == 27 ( Not working )
  • e.key == 'Escape' ( Not working )
  • e.key == 'Esc' ( Not working )

UPDATE:

I have managed to get it working.
Check my answer: HERE

3 Answers 3

4

On the input element

and in my function,

  • I used e.key == 'Escape' as the condition to my if() statement.

and it worked.

For some reason which I didn't bother to understand, Enter seems to work on onKeyPress while Escape doesn't.

Sign up to request clarification or add additional context in comments.

Comments

0

You will get key code via :

const code = event.keyCode || event.which;

class App extends React.Component {
    state={code:''};
   
    onKeyPress(event) {
     const code = event.keyCode || event.which;  
     this.setState({code})
    }
  
    render() {
      return (
        <div>
         <input onKeyPress={this.onKeyPress.bind(this)} />
         <span> Key Code :  {this.state.code}</span>
        </div>
        
      )
    }
  
}

ReactDOM.render(<App />, document.querySelector('section'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
 <section />

Comments

0
 function useKeyPress(keys, onPress) {
  keys = keys.split(' ').map((key) => key.toLowerCase())
  const isSingleKey = keys.length === 1
  const pressedKeys = useRef([])

  const keyIsRequested = (key) => {
    key = key.toLowerCase()
    return keys.includes(key)
  }

  const addPressedKey = (key) => {
    key = key.toLowerCase()
    const update = pressedKeys.current.slice()
    update.push(key)
    pressedKeys.current = update
  }

  const removePressedKey = (key) => {
    key = key.toLowerCase()
    let update = pressedKeys.current.slice()
    const index = update.findIndex((sKey) => sKey === key)
    update = update.slice(0, index)
    pressedKeys.current = update
  }

  const downHandler = ({ key }) => {
    const isKeyRequested = keyIsRequested(key)
    if (isKeyRequested) {
      addPressedKey(key)
    }
  }

  const upHandler = ({ key }) => {
    const isKeyRequested = keyIsRequested(key)
    if (isKeyRequested) {
      if (isSingleKey) {
        pressedKeys.current = []
        onPress()
      } else {
        const containsAll = keys.every((i) => pressedKeys.current.includes(i))
        removePressedKey(key)
        if (containsAll) {
          onPress()
        }
      }
    }
  }

  useEffect(() => {
    window.addEventListener('keydown', downHandler)
    window.addEventListener('keyup', upHandler)
    return () => {
      window.removeEventListener('keydown', downHandler)
      window.removeEventListener('keyup', upHandler)
    }
  }, [])
}

Use it like this:

function testUseKeyPress() {
 const onPressSingle = () => {
    console.log('onPressSingle!')
  }
  const onPressMulti = () => {
    console.log('onPressMulti!')
  }

  useKeyPress('a', onPressSingle)
  useKeyPress('shift h', onPressMulti)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.