The Event Object
React gives handlers the event object, just as the browser did in the JavaScript course. If the handler has a parameter, it gets it:
function handleAnswer(event) {
console.log(event.target.textContent);
}
return (
<p>
<button onClick={handleAnswer}>Yes</button>
<button onClick={handleAnswer}>No</button>
</p>
);A click on No prints No. event.target is the element where the event happened, here the clicked button, so one handler can serve several elements and still tell them apart.
Text fields have the event onChange. In React, it comes after every change of the text, as the event input did in the JavaScript course: after each letter typed or deleted. (The browser's own change event waits until you leave the field. React's onChange doesn't.) event.target is then the field, and event.target.value is what's in it:
<input onChange={(event) => console.log(event.target.value)} />This handler is an arrow function written right in the JSX. React calls it with the event object, just as it would call a named function. Typing Owl prints three lines:
O
Ow
OwlA handler of one short line can stay in the JSX like this. Once it's longer, give it a name and write it above the return, as handleAnswer is.
For now, the handlers only print. Showing what's typed on the page needs state, which is the next lesson, and text fields get a lesson of their own after it, Forms.
Instructions
Write a function handleTicket(event) that prints Ticket: Weekend, with the text of the clicked button instead of Weekend. Make it the click handler of all three buttons.
Give the text field an onChange handler, an arrow function that prints what's in the field. Type your name and watch the console.