react js-tutorial

React Events

An event is a potential action that might be brought on by a user action or a system-generated event. Events include things like mouse clicks, web page loads, key presses, window resizing, and other interactions.

React features a built-in event handling framework that is quite similar to how DOM element events are handled. Synthetic Events is the name given to the react event handling system. A cross-browser wrapper for the native event of the browser is the synthetic event.

Handling events with react have some syntactic differences from handling events on DOM. These are:

  • React events are named as camelCase instead of lowercase.
  • With JSX, a function is passed as the event handler instead of a string.

Example

In the below example, we have used only one component and adding an onChange event. This event will trigger the changeText function, which returns the company name.

import React, { Component } from 'react';  
class App extends React.Component {  
    constructor(props) {  
        super(props);  
        this.state = {  
            companyName: ''  
        };  
    }  
    changeText(event) {  
        this.setState({  
            companyName: event.target.value  
        });  
    }  
    render() {  
        return (  
            <div>  
                <h2>Simple Event Example</h2>  
                <label htmlFor="name">Enter company name: </label>  
                <input type="text" id="companyName" onChange={this.changeText.bind(this)}/>  
                <h4>You entered: { this.state.companyName }</h4>  
            </div>  
        );  
    }  
}  
export default App;  

Output

When you execute the above code, you will get the following output.

After entering the name in the textbox, you will get the output as like below screen.

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.