Handling a button click event

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:

  1. 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.
  1. 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 ...
  1. 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.181.132