Event handling in React
Event handling is a crucial aspect of React, as it allows you to respond to user actions such as clicks, mouse movements, and key presses. In React, you can handle events by providing a callback function to the event handler, which will be called whenever the event occurs.
In React, event handlers are added as props to the elements in the render method. The name of the event handler prop is in camelCase, and the value should be a reference to the function that should be called when the event occurs.
Here's an example of event handling in React:
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = { isToggled: false };
}
handleClick = () => {
this.setState({ isToggled: !this.state.isToggled });
};
render() {
return (
<div>
<button onClick={this.handleClick}>
{this.state.isToggled ? "On" : "Off"}
</button>
</div>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById("root")
);
In this example, the Toggle
component has a state with a single property, isToggled
, which starts as false
. The handleClick
method is used to update the state whenever the button is clicked. The render
method returns a button element with an onClick
prop, which is set to the handleClick
function.
To summarize, event handling in React involves adding event handler props to elements in the render method, and providing a callback function to be called when the event occurs. The state of the component can be updated in response to events to update the UI.
Leave a Comment