[React] Toggle (Show/Hide) HTML Element


React is gaining more and more popularity now [1] [2], so I decide to try it out with my favorite exercise: Toggle (Show/Hide) HTML DOM element.

Demo

JSX code:

app.jsx | repository | view raw
 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
function contentClass(isShow) {
  if (isShow) {
    return "content";
  }
  return "content invisible";
}

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isShow: false};
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(function(prevState) {
      return {isShow: !prevState.isShow};
    });
  }

  render() {
    return (
      <div>
        <div className='control' onClick={this.handleClick}>Click me to toggle</div>
        <div className={contentClass(this.state.isShow)}>contents</div>
      </div>
    );
  }
}

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);

The following is key points in the code:

  • Two HTML div elements (line 24 and 25): one is control element and the other is content element. When users click on the control element, the content element will be shown if it's hidden, will be hidden if it's shown.
  • A boolean state called isShow is defined (line 11). The onClick event of control element will toggle this state (line 15~19).
  • If isShow is true, the invisible class will be added to content element (line 1~6), which makes the content element disappear.

CSS code:

style.css | repository | view raw
1
2
3
.control:hover {cursor: pointer;}
.content {width: 200px; height: 200px; background: yellow;}
.invisible {display: none;}

HTML code:

<div id="root">
  <!-- This div's content will be managed by React. -->
</div>

Tested on: CodePen


References:

[1]Why I moved from Angular to React | Hacker News
[2]谁是 2016 年的 JavaScript 之最? - 开源中国社区