Skip to content

Instantly share code, notes, and snippets.

@benkissi
Last active April 15, 2019 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benkissi/ad088a429f174bdec72852d20d66207a to your computer and use it in GitHub Desktop.
Save benkissi/ad088a429f174bdec72852d20d66207a to your computer and use it in GitHub Desktop.
Context blog
import React, { Component } from "react";
const AppContext = React.createContext();
class AppProvider extends Component {
constructor(props) {
super(props);
this.state = {
todos: []
};
this.addTodo = this.addTodo.bind(this);
this.completed = this.completed.bind(this);
}
addTodo(todo) {
const { todos } = this.state;
const newTodo = {
id: Math.floor(Math.random() * (1000 - 1)) + 1,
todo: todo,
createdAt: Date.now(),
completed: false
};
this.setState({
todos: todos.concat(newTodo)
});
}
completed(id) {
const { todos } = this.state;
todos.forEach(todo => {
if (todo.id === id) {
todo.completed = !todo.completed;
}
});
this.setState({
todos: todos
});
}
render() {
return (
<AppContext.Provider
value={{
todos: this.state.todos,
addTodo: this.addTodo,
completed: this.completed
}}
>
{this.props.children}
</AppContext.Provider>
);
}
}
const AppConsumer = AppContext.Consumer;
export { AppProvider, AppConsumer };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment