Skip to content

Instantly share code, notes, and snippets.

@batazo
Forked from JeromeFranco/pd-with-context-api.js
Created August 30, 2021 16:28
Show Gist options
  • Save batazo/0879081dae10a70d9fd1a686af209a02 to your computer and use it in GitHub Desktop.
Save batazo/0879081dae10a70d9fd1a686af209a02 to your computer and use it in GitHub Desktop.
// 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