React Events
React event handling is accomplished using React events attributes and event handler functions. React event attributes are similar to HTML event attributes, except that React events are named using camelCase.
<button onClick={activateLaser}>
Activate Laser
</button>
The event handler function is defined within the component function and will be invoked when the event occurs.
function App () {
function activateLaser() {
alert('Laser Activated!')
}
return (
<button onClick={activateLaser}>
Activate Laser
</button>
)
}
Passing arguments to React event handlers is common practice but must be accomplished from within a function.
function LaserButton (props) {
function activateLaser(power) {
alert(`Laser is set to ${power}`)
}
return (
<button onClick={(e) => activateLaser(props.power)}>
{props.power}
</button>
)
}