- React events are actions that occur in the user interface, such as a button click,mouse over, a form submission, or a key press. React provides a way to handle these events by using event handlers.
- An event handler is a function that is executed in response to a specific event.
- In React, you can pass an event handler to a component as a prop and bind it to a DOM element using the on syntax, followed by the name of the event
Example code for button click event:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import React,{useState} from 'react'; import ReactDOM from 'react-dom/client'; //App function component function App() { const [count, setCount] = useState(0); //useState hook, initializing count with 0 value let onSubmit = () => { setCount(count + 1) } return ( <> <h2>Example of react event</h2> <div>Fruit count is : {count} </div> <button onClick={onSubmit}> Increment</button> </> ) } const root = ReactDOM.createRoot(document.getElementById("root")); //creating a root React component in your application root.render(<App />) // rendering React components into a DOM node. |
Output:
