Last active
November 12, 2018 08:10
-
-
Save kotarella1110/469073425b7cba77a7ef4a1e7dc0768f to your computer and use it in GitHub Desktop.
React counter component comparing JavaScript and TypeScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
class Counter extends React.Component { | |
state = { | |
counter: 0, | |
}; | |
handleIncrement = () => { | |
this.setState(state => ({ | |
counter: state.counter + 1, | |
})); | |
}; | |
handleDecrement = () => { | |
this.setState(state => ({ | |
counter: state.counter - 1, | |
})); | |
}; | |
render() { | |
const { title } = this.props; | |
const { counter } = this.state; | |
return ( | |
<div> | |
<h1>{title}</h1> | |
<p>Clicked: {counter} times</p> | |
<button onClick={this.handleIncrement}>+</button> | |
<button onClick={this.handleDecrement}>-</button> | |
</div> | |
); | |
} | |
} | |
export default Counter; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
interface IProps { | |
readonly title: string; | |
} | |
interface IState { | |
readonly counter: number; | |
} | |
class Counter extends React.Component<IProps, IState> { | |
public readonly state = { | |
counter: 0, | |
}; | |
private handleIncrement = () => { | |
this.setState(state => ({ | |
counter: state.counter + 1, | |
})); | |
}; | |
private handleDecrement = () => { | |
this.setState(state => ({ | |
counter: state.counter - 1, | |
})); | |
}; | |
public render() { | |
const { title } = this.props; | |
const { counter } = this.state; | |
return ( | |
<div> | |
<h1>{title}</h1> | |
<p>Clicked: {counter} times</p> | |
<button onClick={this.handleIncrement}>+</button> | |
<button onClick={this.handleDecrement}>-</button> | |
</div> | |
); | |
} | |
} | |
export default Counter; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment