Skip to content

Instantly share code, notes, and snippets.

@mikebridge
Created April 28, 2017 20:33
Show Gist options
  • Save mikebridge/b1d4f195dfa7b6fc8f0ae31682c8fcf8 to your computer and use it in GitHub Desktop.
Save mikebridge/b1d4f195dfa7b6fc8f0ae31682c8fcf8 to your computer and use it in GitHub Desktop.
An example react component in TypeScript
import * as React from "react";
import * as PropTypes from "prop-types";
interface IExampleComponentProps {
text?: string;
onCounterIncrease: (count: number) => void;
}
interface IExampleComponentState {
clicks: number;
}
const initialState: IExampleComponentState = {
clicks: 0
};
export class ExampleComponent extends React.Component<IExampleComponentProps, IExampleComponentState> {
// propTypes is unnecessary
static propTypes = {
text: PropTypes.string,
onCounterIncrease: PropTypes.func.isRequired
};
static defaultProps = {
text: "World"
};
constructor(props: IExampleComponentProps) {
super(props);
this.state = initialState;
this.onClick = this.onClick.bind(this);
}
componentDidUpdate(prevProps: IExampleComponentProps, prevState: IExampleComponentState): void {
if (this.props.onCounterIncrease) {
this.props.onCounterIncrease(this.state.clicks);
}
}
public render(): JSX.Element {
return (
<div>
<div className="hello">Hello, {this.props.text}!</div>
<div>Clicks: {this.state.clicks}</div>
<button onClick={this.onClick} >Increase</button>
</div>
);
}
private onClick(): void {
const newClicks = this.state.clicks + 1;
this.setState({ clicks: newClicks });
}
}
export default ExampleComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment