Events in React
Imagine you have a button on a webpage. When a user clicks it, you want something to happen – maybe a counter increases, a form submits, or a menu opens. How does your code know that the user clicked? This is where **events** come into play.
What are Events in React?
Events are actions or occurrences that happen in the browser, usually triggered by the user. Common events include clicking, typing, hovering, submitting forms, and many more. React provides a way to handle these events and respond to them.
React events are named using camelCase, not lowercase. For example, `onClick` instead of `onclick`, and `onSubmit` instead of `onsubmit`.
Handling Events in React
In React, you handle events by passing a function as a prop to the element, not by using strings like in HTML.
HTML (traditional way):
<button onclick="handleClick()">Click me</button>React way:
function MyButton() { function handleClick() { console.log('Button clicked!'); }
return ( <button onClick={handleClick}>Click me</button> );}Notice the differences:
- Event name is `onClick` (camelCase) instead of `onclick`
- Event handler is passed as a function `{handleClick}` not as a string `"handleClick()"`
Common React Events
| Event Name | Triggered When | Common Element |
|---|---|---|
| onClick | Element is clicked | button, div, any element |
| onChange | Input value changes | input, select, textarea |
| onSubmit | Form is submitted | form |
| onMouseEnter | Mouse enters element | any element |
| onMouseLeave | Mouse leaves element | any element |
| onFocus | Element receives focus | input, button |
| onBlur | Element loses focus | input, button |
Example: Multiple Events
function EventDemo() { const [text, setText] = useState(''); const [isHovered, setIsHovered] = useState(false);
function handleClick() { alert('Button clicked!'); }
function handleChange(event) { setText(event.target.value); }
function handleMouseEnter() { setIsHovered(true); }
function handleMouseLeave() { setIsHovered(false); }
return ( <div> <input type="text" value={text} onChange={handleChange} placeholder="Type something..." /> <button onClick={handleClick} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} style={{ backgroundColor: isHovered ? 'lightblue' : 'white' }} > Click or hover me </button> <p>You typed: {text}</p> </div> );}Two Minute Drill
- Events in React are user-triggered actions like clicks, typing, or form submissions.
- React events use camelCase naming (`onClick`, `onChange`, `onSubmit`).
- Event handlers are passed as functions inside curly braces, not as strings.
- Common events: `onClick`, `onChange`, `onSubmit`, `onMouseEnter`, `onMouseLeave`, `onFocus`, `onBlur`.
- You can attach multiple event handlers to the same element.
- Events make your React apps interactive and responsive to user actions.
Need more clarification?
Drop us an email at career@quipoinfotech.com
