Created
August 20, 2018 15:22
-
-
Save mbeaudru/7700e4cb5f321ec5ccc9141876c077ff to your computer and use it in GitHub Desktop.
@Medium - Render Props are the new Controllers / Controller sample
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, { Component, Fragment } from "react"; | |
import PropTypes from "prop-types"; | |
class TodosController extends Component { | |
state = { | |
todos: [ | |
{ | |
id: 1, | |
label: "First item" | |
}, | |
{ | |
id: 2, | |
label: "Second item" | |
} | |
] | |
}; | |
onTodoItemClick = todoItem => event => { | |
const todosState = this.state.todos; | |
this.setState({ todos: todosState.filter(({ id }) => id !== todoItem.id) }); | |
}; | |
onTodoItemCreate = todoItem => { | |
const todosState = this.state.todos; | |
this.setState({ todos: [...todosState, todoItem] }); | |
}; | |
render() { | |
const { as: AsComponent } = this.props; | |
const { todos } = this.state; | |
const childrenProps = { | |
todos, | |
onClick: this.onTodoItemClick, | |
onCreate: this.onTodoItemCreate | |
}; | |
return <AsComponent>{this.props.children(childrenProps)}</AsComponent>; | |
} | |
} | |
TodosController.propTypes = { | |
children: PropTypes.func.isRequired, | |
as: PropTypes.oneOfType([PropTypes.element, PropTypes.node]) | |
}; | |
TodosController.defaultProps = { | |
as: Fragment | |
}; | |
export default TodosController; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment