React JS onClick event handler

Events are triggered by HTML elements to signal important changes, such as when the user clicks a button. Handling events in React is similar to using the Domain Object Model API. The DOM API onclick property is expressed as onClick in React applications and handle the click event which is triggered when the user clicks an element. However, the expression for handling an event property is a function which will be invoked when the specified event is triggered.

Create React App

Type the following command to create a new react app:

npx create-react-app demo

Now, go to the project folder:

cd demo

Now, update default App.js with below code snippet


import React, { Component } from 'react';
class App extends Component {
  constructor(props) {
    this.state = {
        message: "Default Content"
  render() {
    return (
        <div className="h1 bg-secondary text-white text-center p-2">
          { this.state.message }
        <div className="text-center">
          <button className="btn btn-secondary" onClick={ () => this.setState({ message: "Clicked!"})}>
            Click Me
export default App;
When the button element is clicked, the click event gets triggered, and React will invoke the inline function, which calls the setState method to change the value of the message state data property.
Most Helpful This Week