Jacob Goh Jacob Goh - 2 months ago 42
Javascript Question

How to detect 'Shift + Enter' in ReactJS onKeyPress event?

How to detect 'Shift + Enter' in ReactJS onKeyPress event?

Is it possible ?

https://jsfiddle.net/jacobgoh101/cyLqfcts/3/

class App extends React.Component {
constructor(props) {
super(props);
this.handleKeyPress = this.handleKeyPress.bind(this);
}
handleKeyPress(e) {
console.log(e.key);
$('#app').append("<br/>" + e.key);
}
render() {
return ( < textarea defaultValue = {
""
}
onKeyPress = {
this.handleKeyPress
}
/>
);
}
}

ReactDOM.render(<App/>, document.getElementById('app'));

Answer

Your answer is detecting on 'Enter' not 'Shift+Enter'. This should help! https://jsfiddle.net/Pranesh456/c2hzt27g/3/

class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleKeyPress = this.handleKeyPress.bind(this);
  }
  handleKeyPress(e) {
    if (e.nativeEvent.keyCode === 13) {         
        if(e.nativeEvent.shiftKey){
            $('#app').append("<br/> Detected Shift+Enter")
        }
    }
  }
  render() {
    return ( < textarea defaultValue = {
        ""
      }
      onKeyUp = {
        this.handleKeyPress
      }
      />
    );
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));