article

Wednesday, August 18, 2021

ReactJS Events

ReactJS Events

An event is an action that could be triggered as a result of the user action or system generated event. For example, a mouse click, loading of a web page, pressing a key, window resizes, and other interactions are called events.

React events are written in camelCase syntax:

onClick instead of onclick.

React event handlers are written inside curly braces:

onClick={shoot}  instead of onClick="shoot()".
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React from 'react';
//React Events
class App extends React.Component {
  //Event Handlers
  //shoot() {
  //  alert("Great Shot!");
  //}
  shoot = (a) => {
    alert(a);
  }
  render() {
    return (
      <div>
        <h1>Hello, world! React Events</h1>
      <button onClick={this.shoot}>Take the shot!</button> <br/>
      <button onClick={() => this.shoot("Passing Arguments - If you want to send parameters into an event handler, you have two options")}>Take the shot!</button>
      </div>
    );
  }
}
export default App;
Example 2
src/App.js
//src/App.js
import React from 'react';
//React Events
class App extends React.Component {
  constructor(props) {
     super(props);
     
     this.state = {
        data: 'Initial data...'
     }
     this.updateState = this.updateState.bind(this);
  };
  //onClick event that will trigger updateState function once the button is clicked.
  updateState() {
     this.setState({data: 'Data updated...'})
  }
  render() {
     return (
        <div>
           <button onClick = {this.updateState}>CLICK</button>
           <h4>{this.state.data}</h4>
        </div>
     );
  }
}
export default App;
Example 3
src/App.js
//src/App.js
import React from 'react';
//React Events
class App extends React.Component {
  constructor(props) {
     super(props);
     
     this.state = {
        data: 'Initial data...'
     }
     this.updateState = this.updateState.bind(this);
  };
  updateState() {
     this.setState({data: 'Data updated from the child component...'})
  }
  render() {
     return (
        <div>
           <Content myDataProp = {this.state.data} 
              updateStateProp = {this.updateState}></Content>
        </div>
     );
  }
}
//Child Events
class Content extends React.Component {
  render() {
     return (
        <div>
           <button onClick = {this.props.updateStateProp}>CLICK</button>
           <h3>{this.props.myDataProp}</h3>
        </div>
     );
  }
}
export default App;
Example 4
src/App.js
//src/App.js
import React from 'react';
//React Events
class App extends React.Component {
  render() {
     return (
        <div>
          <form onSubmit={handleSubmit}>
            <button type="submit">Submit</button>
          </form>
        </div>
     );
  }
}
function handleSubmit(e) {
  e.preventDefault();
  console.log('You clicked submit.');
}
export default App;
Example 5
src/App.js
//src/App.js
import React from 'react';
//React Events
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};
    //this Toggle component renders a button that lets the user toggle between “ON” and “OFF” states
    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}
export default App;
Example 6 src/App.js
//src/App.js
import React from 'react';
//React Events
class App extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={() => this.handleClick()}>
        Click me
      </button>
    );
  }
}
export default App;
Example 7
src/App.js
//src/App.js
import React from 'react';
//React Events
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: ""
    };
  }
  //event handlers
  changeText(event) {
      this.setState({
      name: event.target.value
    });
  }
  render() {
    return (
      <div>
      <label htmlFor="name">Enter Text here </label>
      <input type="text" id="name" onChange={this.changeText.bind(this)} />
      <h3>{this.state.name}</h3>
      </div>
    );
  }
}
export default App;
Example 8 src/App.js
//src/App.js
import React from 'react';
//React Events
class App extends React.Component {
  constructor(props) {  
    super(props);  
    this.state = {  
        yourName: ''  
    };  
}  
changeText(event) {  
    this.setState({  
      yourName: event.target.value  
    });  
}  
render() {
    return (
      <div>  
      <h2>Simple Event Example</h2>  
      <label htmlFor="name">Enter Your name: </label>  
      <input type="text" id="yourName" onChange={this.changeText.bind(this)}/>  
      <h4>You entered: { this.state.yourName }</h4>  
      </div>
    );
  }
}
export default App;

Related Post