Learn how to interact with events in React applications
React provides a simple way to manage events. Ready to say goodbyeaddEventListener
.
In the previous article on countries, you saw the following example:
const CurrencySwitcher = props => {
return (
<button onClick={props.handleChangeCurrency}>
Current currency is {props.currency}. Change it!
</button>
)
}
If you’ve been using JavaScript for a while, it’s just like the old oneJavaScript event handler, Except this time you want to use JavaScript instead of HTML to define everything, and you want to pass functions instead of strings.
The actual event name is different because in React, you use camelCase for everything, soonclick
becomeonClick
,onsubmit
becomeonSubmit
.
For reference, this is old-style HTML with JavaScript events mixed in:
<button onclick="handleChangeCurrency()">...</button>
Event handler
By convention, the event handler is defined as a method of the Component class:
class Converter extends React.Component {
handleChangeCurrency = event => {
this.setState({ currency: this.state.currency === '€' ? '