Using Events in React Js
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 ( {/* Display the count */}); } } export default App;Count: {this.state.count}
{/* Add a button with an onClick event that calls the handleClick function */}