Brady Dowling
Brady Dowling

Reputation: 5522

Can't call e.preventDefault on React element (div)

I'm building a fake text area that supports highlighting and cursor navigation. As part of this, I need to support keyboard shortcuts like Alt + left/right keys. In order to do this, I want to prevent the default browser actions from happening (in Firefox on Windows Alt + left/right navigates forward or back a page).

The issue is that the event object that is passed to my onKeyDownHandler function doesn't contain the preventDefault method. How can I get access to this method?

Here's a simplified version of my code:

import React from 'react';

class FakeTextArea extends React.Component {
  constructor(props) {
    super(props);

    this.onKeyDownHandler = this.onKeyDownHandler.bind(this);
  }

  onKeyDownHandler(e) {
    if (e.key === 'arrowleft' && e.altKey) {
      // e.preventDefault() doesn't exist
      console.log('no prevent default?');
    }
  }

  render() {
    return (
      <div
        tabIndex="0"
        onKeyDown={this.onKeyDownHandler}
      >
      Here is some random text that I want to have in here
      </div>
    );
  }
}

export default FakeTextArea;

Upvotes: 1

Views: 609

Answers (1)

Kaio Duarte
Kaio Duarte

Reputation: 133

[UPDATE] The event is just not visible, but it's there, you can find it with an old and great console.log(e.preventDefault)!

[OLD ANSWER] Use the event from nativeEvent:

onKeyDownHandler(e) {
    if (e.key === 'arrowleft' && e.altKey) {
      e.nativeEvent.preventDefault()
      console.log('no prevent default?');
    }
  }

Reference: https://reactjs.org/docs/events.html#overview

Upvotes: 2

Related Questions