8. Use Event Handlers

8.1. Toggle Method

To show or hide the answer we will add a toggle handler to the class FaqItem.jsx. This method needs to be bound to the instance like this:

11constructor(props) {
12  super(props);
13  this.state = {
14    show: false
15  };
16}

8.2. Exercise

Write the toggle handler which will toggle the show state variable and set the new state using the setState method:

Solution

19toggle = () => {
20  this.setState({
21    show: !this.state.show
22  });
23}

8.3. Click Handler

To call the newly created toggle method we will add an on click handler to the question:

25render() {
26  return (
27    <li className="faq-item">
28      <h2 onClick={this.toggle} className="question">
29        {this.props.question}
30      </h2>
31      {this.state.show && <p>{this.props.answer}</p>}
32    </li>
33  );
34}

Differences

FaqItem.jsx

--- a/src/components/FaqItem.jsx
+++ b/src/components/FaqItem.jsx
@@ -10,15 +10,24 @@ class FaqItem extends Component {

  constructor(props) {
    super(props);
    this.state = {
      show: false
    };
  }

+  toggle = () => {
+    this.setState({
+      show: !this.state.show
+    });
+  }
+
  render() {
    return (
      <li className="faq-item">
-        <h2 className="question">{this.props.question}</h2>
+        <h2 onClick={this.toggle} className="question">
+          {this.props.question}
+        </h2>
        {this.state.show && <p>{this.props.answer}</p>}
      </li>
    );
 1import React, { Component } from "react";
 2import PropTypes from "prop-types";
 3import "./FaqItem.css";
 4
 5class FaqItem extends Component {
 6  static propTypes = {
 7    question: PropTypes.string.isRequired,
 8    answer: PropTypes.string.isRequired
 9  };
10
11  constructor(props) {
12    super(props);
13    this.state = {
14      show: false
15    };
16  }
17
18  toggle = () => {
19    this.setState({
20      show: !this.state.show
21    });
22  }
23
24  render() {
25    return (
26      <li className="faq-item">
27        <h2 onClick={this.toggle} className="question">
28          {this.props.question}
29        </h2>
30        {this.state.show && <p>{this.props.answer}</p>}
31      </li>
32    );
33  }
34}
35
36export default FaqItem;