React TextArea - Handle the Keyboard Events

The TextArea raises four keyboard events: keyDown, keyUp and enterKey. Within the functions that handle them, you can access the original keyboard events. If you are not going to change the functions during the lifetime of the UI component, assign them to the respective UI component properties.

  • import React from 'react';
  • import 'devextreme/dist/css/dx.light.css';
  •  
  • import { TextArea } from 'devextreme-react/text-area';
  •  
  • class App extends React.Component {
  • render() {
  • return (
  • <TextArea
  • onKeyDown={this.onKeyDown}
  • onKeyUp={this.onKeyUp}
  • onEnterKey={this.onEnterKey}
  • />
  • );
  • }
  •  
  • onKeyDown(e) {
  • const keyCode = e.event.key;
  • // Event handling commands go here
  • }
  • onKeyUp(e) {
  • const keyCode = e.event.key;
  • // Event handling commands go here
  • }
  • onEnterKey(e) {
  • // Event handling commands go here
  • }
  • }
  •  
  • export default App;

Use the registerKeyHandler(key, handler) method to implement a custom handler for a key.

App.js
  • import React from 'react';
  • import 'devextreme/dist/css/dx.light.css';
  •  
  • import { TextArea } from 'devextreme-react/text-area';
  •  
  • class App extends React.Component {
  • constructor(props) {
  • super(props);
  •  
  • this.textAreaRef = React.createRef();
  • }
  •  
  • render() {
  • return (
  • <TextArea ref={this.textAreaRef} />
  • );
  • }
  •  
  • get textArea() {
  • return this.textAreaRef.current.instance;
  • }
  •  
  • componentDidMount() {
  • this.textArea.registerKeyHandler('backspace', function(e) {
  • // The argument "e" contains information on the event
  • });
  • this.textArea.registerKeyHandler('space', function(e) {
  • // ...
  • });
  • }
  • }
  •  
  • export default App;
See Also