Skip to content

Instantly share code, notes, and snippets.

@elias551
Last active September 19, 2017 15:43
Show Gist options
  • Save elias551/69263782a66d5c73c3b77450096c7724 to your computer and use it in GitHub Desktop.
Save elias551/69263782a66d5c73c3b77450096c7724 to your computer and use it in GitHub Desktop.
Minimal redux-typescript format
import * as React from "react";
import * as ReactDOM from "react-dom";
import { createStore, Action, Dispatch } from "redux";
import { Provider, connect } from "react-redux";
enum ActionType {
Increment = "INCREMENT",
Decrement = "DECREMENT"
}
interface AppAction extends Action {
type: ActionType;
}
const increment = () => ({
type: ActionType.Increment
});
const decrement = () => ({
type: ActionType.Decrement
});
interface ReduxState {
value: number;
}
const initialState: ReduxState = { value: 0 };
const reducer = (state: ReduxState = initialState, action: AppAction) => {
switch (action.type) {
case ActionType.Increment:
return { value: state.value + 1 };
case ActionType.Decrement:
return { value: state.value - 1 };
default:
return state;
}
};
interface ComponentProps {
value: number;
increment: () => void;
decrement: () => void;
}
const App: React.StatelessComponent<ComponentProps> = props => {
return (
<div>
The value is: {props.value}
<br />
<button onClick={props.increment}>increment</button>
<br />
<button onClick={props.decrement}>decrement</button>
</div>
);
};
const mapStateToProps = (state: ReduxState) => state;
const mapDispatchToProps = (dispatch: Dispatch<ReduxState>) => ({
increment: () => {
dispatch(increment());
},
decrement: () => {
dispatch(decrement());
}
});
const AppComponent = connect(mapStateToProps, mapDispatchToProps)(App);
const store = createStore(reducer);
ReactDOM.render(
<Provider store={store}>
<AppComponent />
</Provider>,
document.getElementById("root") as HTMLElement
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment