In this section, we are going to implement an event listener on the Ask a question button in the HomePage component. Follow these steps to do so:
- Open HomePage.tsx and add a click event listener to the PrimaryButton instance in the JSX:
<PrimaryButton onClick={handleAskQuestionClick}>
Ask a question
</PrimaryButton>
Event listeners in JSX can be attached using a function prop that is named with on before the native JavaScript event name in camel case. So, a native click event can be attached using an onClick function prop. React will automatically remove the event listener for us before the element is destroyed.
- Let's implement the handleAskQuestionClick function, just above the return statement in the HomePage component:
const handleAskQuestionClick = () => {
console.log('TODO - move to the AskPage');
};
return ...
- If we click on the Ask a question button in the running app, we'll see the following message in the console:
So, handling events in React is super easy! In Chapter 4, Routing with React Router, we'll finish off the implementation of the handleAskQuestionClick function and navigate to the page where a question can be asked.