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
Component displays Height and Width on window resize
React Components
3 Different Examples - How State Works in React?
Integrate Bootstrap with ReactJS Application
Display JSON Data in React JS
How to render raw HTML content in React JS?
Example of React Bootstrap Datatable
How to show hide component on Click in React JS?
Embed JavaScript Expressions in JSX
How to use arrow function in React stateless components?