Chapter 6: Handling Events
Working with Event Handlers in React
React components can attach event listeners to DOM elements using event handler functions. These functions are triggered when the corresponding event occurs on the element.
Here's the basic syntax for attaching an event handler:
function Button() {
const handleClick = () => {
console.log('Button clicked!');
};
return (
<button onClick={handleClick}>Click me</button>
);
}
In this example:
- We define a "handleClick" function that logs a message to the console when clicked.
- The "button" element has an "onClick" attribute set to the "handleClick" function. This tells React to call "handleClick" whenever the button is clicked.
Passing Event Data to Components
Event handler functions can receive an event object as an argument, containing information about the event that occurred. This data can be used within the handler to react to the specific details of the user interaction.
function Input(props) {
const handleChange = (event) => {
props.onChange(event.target.value); // Pass the input value to the parent component
};
return (
<input type="text" onChange={handleChange} />
);
}
This example demonstrates passing the input value to a parent component:
- The "Input" component receives an "onChange" prop as a function from its parent.
- The "handleChange" function within "Input" retrieves the current input value from the event object's "target.value" property.
- It then calls the "onChange" prop function (passed from the parent) and provides the input value as an argument, enabling communication between components.
Building Interactive Elements
By combining event handling with state management and conditional rendering, you can build interactive UI elements that respond to user input and update the application's state. This allows you to create dynamic and engaging user experiences.
We'll explore more advanced event handling techniques and explore building complex interactive features in the following chapters. Stay tuned!
Next page: Using CSS