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:

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

8.2. Exercise

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

Solution

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

8.3. Click Handler

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

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

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.toggle = this.toggle.bind(this);
    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>
    );
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import React, { Component } from "react";
import PropTypes from "prop-types";
import "./FaqItem.css";

class FaqItem extends Component {
  static propTypes = {
    question: PropTypes.string.isRequired,
    answer: PropTypes.string.isRequired
  };

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

  toggle() {
    this.setState({
      show: !this.state.show
    });
  }

  render() {
    return (
      <li className="faq-item">
        <h2 onClick={this.toggle} className="question">
          {this.props.question}
        </h2>
        {this.state.show && <p>{this.props.answer}</p>}
      </li>
    );
  }
}

export default FaqItem;