9. Use Event Handlers

9.1. Toggle Function

To show or hide the answer, we will add a toggle function to the component FaqItem.jsx.

9.2. Exercise

Write the toggle handler which will toggle the isAnswer state variable and set the new state using the setAnswer function:

Solution

 8  const toggle = () => {
 9    setAnswer(!isAnswer);
10  };

9.3. Click Handler

To call the newly created toggle function, we will add an onClick handler to the question:

12  return (
13    <li className="faq-item">
14      <h2 className="question" onClick={toggle}>
15        {props.question}
16      </h2>
17      {isAnswer && <p>{props.answer}</p>}
18    </li>
19  );

Differences

FaqItem.jsx

--- a/src/components/FaqItem.jsx
+++ b/src/components/FaqItem.jsx
@@ -4,9 +4,16 @@ import PropTypes from "prop-types";

 const FaqItem = (props) => {
   const [isAnswer, setAnswer] = useState(false);
+
+  const toggle = () => {
+    setAnswer(!isAnswer);
+  };
+
   return (
     <li className="faq-item">
-      <h2 className="question">{props.question}</h2>
+      <h2 className="question" onClick={toggle}>
+        {props.question}
+      </h2>
       {isAnswer && <p>{props.answer}</p>}
     </li>
   );
 1import { useState } from "react";
 2import "./FaqItem.css";
 3import PropTypes from "prop-types";
 4
 5const FaqItem = (props) => {
 6  const [isAnswer, setAnswer] = useState(false);
 7
 8  const toggle = () => {
 9    setAnswer(!isAnswer);
10  };
11
12  return (
13    <li className="faq-item">
14      <h2 className="question" onClick={toggle}>
15        {props.question}
16      </h2>
17      {isAnswer && <p>{props.answer}</p>}
18    </li>
19  );
20};
21
22FaqItem.propTypes = {
23  question: PropTypes.string.isRequired,
24  answer: PropTypes.string.isRequired,
25};
26
27export default FaqItem;