JS-React: Event Listener
HTML
<div id="pdiv">
<p>Press Enter</p>
</div>
<div id="app">
</div>
<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)
- class MyComponent extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- message: ""
- };
- this.handleEnter = this.handleEnter.bind(this);
- this.handleKeyPress = this.handleKeyPress.bind(this);
- }
- componentDidMount() {
- document.addEventListener("keydown", this.handleKeyPress);
- }
- componentWillUnmount() {
- document.removeEventListener("keydown", this.handleKeyPress);
- }
- hideP() {
- var x = document.getElementById("pdiv");
- x.style.display = "none";
- }
- handleEnter() {
- this.setState({
- message: this.state.message + "You pressed the enter key! "
- });
- }
- handleKeyPress(event) {
- if (event.keyCode === 13) {
- this.hideP();
- this.handleEnter();
- }
- }
- render() {
- return (
- <div>
- <h1>{this.state.message}</h1>
- </div>
- );
- }
- }
- React.render(<MyComponent />, document.getElementById("app"));
Comments