4

I am using React and I have old-style kind of code for handling some events:

componentDidMount = () => {
   document.addEventListener('mousedown', this.handleClick);
}

componentWillUnmount = () => {
  document.removeEventListener('mousedown', this.handleClick);
}

Is it the right way of setting up event handlers in React? I mean best practice. How would you refactor the above code in the React - way of doing things? I understand when we set up events on individual elements, but I am confused in this particular case.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nikita Vlasenko
  • 4,004
  • 7
  • 47
  • 87

3 Answers3

1

Ideally in React, you never edit the DOM yourself. You should only update the virtual DOM and then let React handle changes to the DOM.

It seems like you want to call this.handleClick() when any part of the document is clicked. One way you could handle that in the "React" way is to add an onClick prop to a container within like so...

class App extends Component {
   constructor() {
      this.handleClick = this.handleClick.bind(this);
   }
   render() {
      return (
         <div className="container" onClick={this.handleClick}=>
            //...the rest of your app
         </div>
      )
   }
}

And then make sure that the margins/padding is set in such a way to make sure that your div covers the whole page.

1

In react you should not bind eventListeners directly to the DOM as react provides synthetic events which can be and should be used and let react handle the rest.

For more details on Synthetic Events here are the React docs

So in your component you can have pass the parameter to your component onMouseDown and handler its click handler something like:

class SomeClass extends Component {
  constructor(props) {
    super(props)

    this.mouseDownHandler = this.mouseDownHandler.bind(this)
  }

  mouseDownHandler() {
    // do something
  }

  render() {
    return (
      <div
        onMouseDown={this.mouseDownHandler}
      >

      </div>
    )
  }
} 

Hope this helps.

warl0ck
  • 3,356
  • 4
  • 27
  • 57
  • OK, but what about these stackoverflow answers: https://stackoverflow.com/questions/19014250/reactjs-rerender-on-browser-resize – Nikita Vlasenko Jan 23 '18 at 20:13
  • 1
    I suppose, events like resize are not in the scope of that current website, so you will have to attach event listeners to window. But these events are in scope of website. – warl0ck Jan 24 '18 at 04:15
-1

Is it the right way of setting up event handlers in React?

What you are doing is perfectly fine.

How would you refactor the above code in the React - way of doing things?

Ideally, you would use the React provided DOM Events when possible, but since this is a global document click listener then your code is correct.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140