Skip to content

Instantly share code, notes, and snippets.

@kotarella1110
Last active November 12, 2018 08:10
Show Gist options
  • Save kotarella1110/469073425b7cba77a7ef4a1e7dc0768f to your computer and use it in GitHub Desktop.
Save kotarella1110/469073425b7cba77a7ef4a1e7dc0768f to your computer and use it in GitHub Desktop.
React counter component comparing JavaScript and TypeScript.
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;
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