React Events

Page Content:
1.Events – Introduction
2Events – Difference Between Normal & React Event Handling

1.Introduction:

1.Event is an action that can be triggered by user action or system-generated action. Ex: mouse click event.
2.React has its own event handling system called Synthetic Events which are similar to DOM event handling.


2.Difference between normal & React Event handling

1.React events are named using camelCase, rather than lowercase.

For Normal HTML:

<button onclick="">

For React:

<button onClick={}>




2.With JSX you pass a function as the event handler, rather than a string.

Example:

HTML Event Handling:

           <button onclick="showMessage()">
                Hello webdev99
           </button>

React Event Handling:

           <button onClick={showMessage}>  
               Hello webdev99  
           </button>  




3.In react we must call preventDefault event explicitly to prevent the default behavior.

For example, with plain HTML, to prevent the default link behavior of opening a new page, you can write:

<a href="#" onclick="console.log('You had clicked a Link.');return false">  
    show-Message
</a>  


In React, we can write it as:

function MyComponent() {  
    function showMessage(e) {  
        e.preventDefault();  
        console.log('You had clicked a Link.');  
    }  
    return (  
        <a href="#" onClick={showMessage}>  
              show-Message  
        </a>  
    );  
}  


Example:

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {Toggle: true};
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(state => ({
      Toggle: !state.Toggle
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.Toggle ? 'ON' : 'OFF'}
      </button>
    );
  }
}

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);


Before click,

After click,