-
-
Save batazo/0879081dae10a70d9fd1a686af209a02 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// TodoPage.js | |
export const TodoContext = createContext({}); | |
class TodoPage extends React.Component { | |
state = { | |
todos: [ | |
{ id: 1, desc: 'Check email', completed: false }, | |
{ id: 2, desc: 'Write blog post', completed: false }, | |
], | |
user: { name: 'John', canDelete: true }, | |
}; | |
handleDelete = todo => { | |
const todos = this.state.todos.filter(t => t.id !== todo.id); | |
this.setState({ todos }); | |
}; | |
render() { | |
const { todos, user } = this.state; | |
return ( | |
<TodoContext.Provider | |
value={{ canDelete: user.canDelete, onDelete: this.handleDelete }} | |
> | |
<div> | |
<TodoList todos={todos} /> | |
</div> | |
</TodoContext.Provider> | |
); | |
} | |
} | |
// TodoList.js | |
const TodoList = ({ todos }) => { | |
return ( | |
<div> | |
<Title value="Todo List" /> | |
<div> | |
{todos.map(todo => ( | |
<TodoItem key={todo.id} todo={todo} /> | |
))} | |
</div> | |
</div> | |
); | |
}; | |
TodoList.propTypes = { | |
todos: PropTypes.array, | |
}; | |
// TodoItem.js | |
const TodoItem = ({ todo }) => { | |
return ( | |
<TodoContext.Consumer> | |
{({ onDelete, canDelete }) => ( | |
<div> | |
<div>{todo.desc}</div> | |
<div> | |
<button disabled={!canDelete} onClick={() => onDelete(todo)} /> | |
</div> | |
</div> | |
)} | |
</TodoContext.Consumer> | |
); | |
}; | |
TodoItem.propTypes = { | |
todo: PropTypes.object, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment