React events: Difference between revisions

From wikinotes
(Created page with "You can subscribe to DOM events with callbacks similarly to javascript.<br> except that events are in camelcase <br> and callbacks are defined as methods rather than strings. React DOM events are abstracted, so they behave the same on all browsers. See [https://reactjs.org/docs/events.html SyntheticEvent docs]. See https://reactjs.org/docs/handling-events.html = Documentation = <blockquote> {| class="wikitable" |- | Event Handling Docs || https://reactjs.org/docs/...")
 
No edit summary
Line 42: Line 42:
</source>
</source>
</blockquote><!-- Example -->
</blockquote><!-- Example -->
= EventHandler Arguments =
<blockquote>
You can bind arguments to the event-handler using lambda expressions in the event-handler.<br>
<syntaxhighlight lang="javascript">
// if the method signature accepta a param, it will be passed the element
<button onClick{(e) => this.deleteRow(id, e)}>Delete Row</button>
</syntaxhighlight>
<syntaxhighlight lang="javascript">
// 'this' refers to the element that triggered the event
<button onClick{this.deleteRow.bind(this, id)}>Delete Row</button>
</syntaxhighlight>
</blockquote><!-- EventHandler Arguments -->

Revision as of 21:09, 10 December 2022

You can subscribe to DOM events with callbacks similarly to javascript.
except that events are in camelcase
and callbacks are defined as methods rather than strings.

React DOM events are abstracted, so they behave the same on all browsers. See SyntheticEvent docs.

See https://reactjs.org/docs/handling-events.html

Documentation

Event Handling Docs https://reactjs.org/docs/handling-events.html
SyntheticEvent Docs https://reactjs.org/docs/events.html

Example

A component, whose element subscribes to the DOM event through onClick.

class HelloWorld extends React.Component {
  sayHello() {
    console.log('hello')
  }

  render() {
    return (
      <button onClick={() => this.sayHello()}> // anonymous callback variation
        Say Hello
      </button>

      <button onClick{sayHello}>               // instance-method callback variation
        Say Hello
      </button>
    );
  }
}

EventHandler Arguments

You can bind arguments to the event-handler using lambda expressions in the event-handler.

// if the method signature accepta a param, it will be passed the element
<button onClick{(e) => this.deleteRow(id, e)}>Delete Row</button>
// 'this' refers to the element that triggered the event
<button onClick{this.deleteRow.bind(this, id)}>Delete Row</button>