Last active
January 16, 2018 09:53
-
-
Save pokorson/958405c6618bebd1654b7f9a03420a13 to your computer and use it in GitHub Desktop.
List stateless with recompose
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"; | |
import { pure, withReducer, compose, withHandlers, mapProps } from "recompose"; | |
import R from "ramda"; | |
import { createReducer } from "./utils"; | |
const ListItem = pure(({ text }) => <li>{text}</li>); | |
const renderItems = R.map(t => <ListItem key={t} text={t} />); | |
const ListComponent = ({ todos, name, updateName, addTodo }) => | |
<div> | |
<input onChange={updateName} value={name} /> | |
<button onClick={() => addTodo(name)}>add todo</button> | |
<ul> | |
{renderItems(todos)} | |
</ul> | |
</div>; | |
const initialState = { todos: [], name: "" }; | |
const listReducer = createReducer({ | |
UPDATE_NAME: (state, payload) => ({ name: payload }), | |
ADD_TODO: (state, payload) => ({ todos: [...state.todos, payload] }) | |
}); | |
const List = compose( | |
withReducer("state", "dispatch", listReducer, initialState), | |
withHandlers({ | |
updateName: ({ dispatch }) => e => | |
dispatch({ type: "UPDATE_NAME", payload: e.target.value }), | |
addTodo: ({ dispatch, name }) => name => | |
dispatch({ type: "ADD_TODO", payload: name }) | |
}), | |
mapProps(({ state, ...props }) => ({ ...state, ...props })) | |
)(ListComponent); | |
export default List; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment