Skip to content

React mutates event objects #2293

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
cjohansen opened this issue Oct 6, 2014 · 2 comments
Closed

React mutates event objects #2293

cjohansen opened this issue Oct 6, 2014 · 2 comments

Comments

@cjohansen
Copy link

I have some code that accesses event.target asynchronously, and to my surprise React is mutating the event object, removing useful properties synchronously after emitting the event. This seems like broken behavior to me:

<!DOCTYPE html>
<html>
  <head>
    <title>React mutating event objects</title>
  </head>
  <body>
    <h1>React mutating event objects</h1>
    <div id="ui"></div>
    <script src="http://fb.me/react-0.11.2.js"></script>
    <script>
      var d = React.DOM;

      var Clicker = React.createClass({
          render: function () {
              return d.div({},
                           d.a({
                               href: "#",
                               onClick: function (e) {
                                   e.preventDefault();
                                   this.setProps({syncTarget: e.target});
                                   setTimeout(function () {
                                       this.setProps({asyncTarget: e.target});
                                   }.bind(this), 10);
                               }.bind(this)
                           }, "Click it"),
                           d.p({}, "Sync target: " + this.props.syncTarget),
                           d.p({}, "Async target: " + this.props.asyncTarget));
          }
      });

      React.renderComponent(Clicker(), document.getElementById("ui"));
    </script>
  </body>
</html>

I would expect the sync and async targets to be the same, but if you run the above, async target will be null.

@dittos
Copy link
Contributor

dittos commented Oct 6, 2014

It happens because React pools event objects. You can call e.persist() to prevent the event object being recycled.

@zpao
Copy link
Member

zpao commented Oct 6, 2014

React doesn't mutate the native object, just our own synthetic event. As mentioned we do poll these objects to mitigate GC and you can hold on to one by calling persist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants