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
src\App.js
import React, { Component } from 'react'; class App extends Component { constructor(props) { super(props); this.state = { message: "Default Content" } } render() { return ( <div> <div className="h1 bg-secondary text-white text-center p-2"> { this.state.message } </div> <div className="text-center"> <button className="btn btn-secondary" onClick={ () => this.setState({ message: "Clicked!"})}> Click Me </button> </div> </div> ); } } 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
Getting Started with React and Hello World Example
Display JSON Data in React JS
React Components
How to build and use a custom react component from scratch?
How to pass an Argument to a Method used inside JSX expression?
React JS get Tag Name and Inner Text on Click
How to perform computation inside expression using ternary operator?
How to create Functional Component?
React Static Website with Material UI theme
React JS update Div content on click