Using Events in React Js | YourSite

Using Events in React Js

React Js • 2272 views

Question

1. Using Events in React Js

• Create a button that will increment the state of a variable count by 1.

• Use onClick event to call a function handleClick, and update the state of the count variable.

• Note: Make sure to use anonymous function using arrow function technique in onClick event to call a function handleClick.

Answer


import React, { Component } from 'react';


class App extends React.Component {
  // Initialize the state with a count variable set to 0
  state = {
    count: 0,
  };

  // This function will be called when the button is clicked
  handleClick = () => {
    // Increment the count by 1
    this.setState({ count: this.state.count + 1 });
  };

  // The render function returns the JSX that should be rendered
  render() {
    return (
      <div>
        {/* Display the count */}
        <p>Count: {this.state.count}</p>
        {/* Add a button with an onClick event that calls the handleClick function */}
        <button onClick={() => this.handleClick()}>Increment</button>
      </div>
    );
  }
}


export default App;

🚀 More Blogs You Might Like

Explore more articles and keep learning

Heat Stroke in Summer: Causes, Symptoms, Prevention and What To Do
health
Heat Stroke in Summer: Causes, Symptoms, Prevention and What To Do

Heat Stroke in Summer: Causes, Symptoms, Prevention and What To Do...

👁 8 2026-04-26
Read More →
Alcoholic Fatty Liver Disease: Causes, Symptoms, Risks and How to Improve It
health
Alcoholic Fatty Liver Disease: Causes, Symptoms, Risks and How to Improve It

Alcoholic Fatty Liver Disease: Causes, Symptoms, Risks and How to Improve It...

👁 9 2026-04-26
Read More →
Non-Alcoholic Fatty Liver: Meaning, Causes, Symptoms, and How to Improve It
health
Non-Alcoholic Fatty Liver: Meaning, Causes, Symptoms, and How to Improve It

Non-Alcoholic Fatty Liver: Meaning, Causes, Symptoms, and How to Improve It...

👁 10 2026-04-26
Read More →
The Ultimate Blueprint to Score 70/70 in ISC Class 12 Computer Science
class-1-12-resources
The Ultimate Blueprint to Score 70/70 in ISC Class 12 Computer Science

The Ultimate Blueprint to Score 70/70 in ISC Class 12 Computer Science...

👁 47 2026-04-11
Read More →