Skip to content

Instantly share code, notes, and snippets.

@esmevane
Created December 20, 2016 15:30
Show Gist options
  • Save esmevane/58b28058ebacc5e1324e399bd420b01f to your computer and use it in GitHub Desktop.
Save esmevane/58b28058ebacc5e1324e399bd420b01f to your computer and use it in GitHub Desktop.
[ Typescript / React ]: Recreating the elm architecture
import * as React from "react";
import { Component } from "react";
const styles: any = require("./styles.module.css");
type None = "None";
type Increment = "Increment";
type Decrement = "Decrement";
type Message = None | Increment | Decrement;
type Model = { total: number };
type Action = { message: Message, model: Model };
type Props = { total: number, onClick: Function };
class Counter extends Component<Props, {}> {
render() {
return(
<div className={ styles.container }>
<button onClick={ this.props.onClick("Increment") }>
+
</button>
<button onClick={ this.props.onClick("Decrement") }>
-
</button>
{ this.props.total }
</div>
);
}
}
const update = (action: Action): Model => {
switch (action.message) {
case "Increment":
return { total: action.model.total + 1 };
case "Decrement":
return { total: action.model.total - 1 };
case "None":
default:
return action.model;
}
};
export default class ConnectCounter extends Component<{}, Model> {
constructor(props) {
super(props);
this.state = { total: 0 };
}
render() {
const onAction = (message: Message): Function => {
return () => {
const action = { message, model: this.state };
console.log(action);
this.setState(update(action));
};
};
return React.Children.only(
<Counter { ...this.state } onClick={ onAction } />
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment