JS-React: Event Listener

HTML
<div id="pdiv">
  <p>Press Enter</p>
</div>
<div id="app">
</div>

CSS(sass)
html, body
  height: 100%
  
body
  background: #333
  display: flex
  justify-content: center
  align-items: center
  font-family: Helvetica Neue
  
h1
  font-size: 2em
  color: lightblue
  display: inline-block
  
p
  font-size: 1.8em
  font-family: Verdana
  color: black


JAVASCRIPT(babel)
  1. class MyComponent extends React.Component {
  2.   constructor(props) {
  3.     super(props);
  4.     this.state = {
  5.       message: ""
  6.     };
  7.     this.handleEnter = this.handleEnter.bind(this);
  8.     this.handleKeyPress = this.handleKeyPress.bind(this);
  9.   }

  10.   componentDidMount() {
  11.     document.addEventListener("keydown", this.handleKeyPress);
  12.   }
  13.   componentWillUnmount() {
  14.     document.removeEventListener("keydown", this.handleKeyPress);
  15.   }

  16. hideP() {
  17.     var x = document.getElementById("pdiv");
  18.         x.style.display = "none";
  19.     
  20. }
  21.   handleEnter() {
  22.     this.setState({
  23.       message: this.state.message + "You pressed the enter key! "
  24.     });
  25.   }
  26.   handleKeyPress(event) {
  27.     if (event.keyCode === 13) {
  28.       this.hideP();
  29.       this.handleEnter();
  30.       
  31.     }
  32.   }
  33.   render() {
  34.     return (
  35.       <div>
  36.         <h1>{this.state.message}</h1>
  37.       </div>
  38.     );
  39.   }
  40. }

  41. React.render(<MyComponent />, document.getElementById("app"));

Comments

Popular posts from this blog

Tech Duos For Web Development

CIFAR-10 Dataset Classification Using Convolutional Neural Networks (CNNs) With PyTorch

Long-short-term-memory (LSTM) Word Prediction With PyTorch