Skip to content

Instantly share code, notes, and snippets.

@pubudu-ranasinghe
Last active November 3, 2019 10:09
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 pubudu-ranasinghe/8427dbae2c713ff0089c3f773f080445 to your computer and use it in GitHub Desktop.
Save pubudu-ranasinghe/8427dbae2c713ff0089c3f773f080445 to your computer and use it in GitHub Desktop.
react-context-example-06
import React, { useState } from "react";
import { ItemList, NewItem } from "./components/Items";
import TodoContext from "./contexts/TodoContext";
import "./App.css";
const initialItems = [
"Setup todo context",
"Consume context from child components"
];
function App() {
const [items, setItems] = useState(initialItems);
function handleAddItem(item) {
setItems([...items, item]);
}
function handleRemoveItem(index) {
const copy = [...items];
copy.splice(index, 1);
setItems(copy);
}
// We wrap the entire application with TodoContext provider, so that it
// provides the value defined here(items and handlers) to the entire component heirachy
// Now we don't need to pass the props to NewItem and ItemList
return (
<TodoContext.Provider
value={{ items, add: handleAddItem, remove: handleRemoveItem }}
>
<div className="App">
<header className="App-header">
<h2>🚀 ToDo App</h2>
<NewItem />
<ItemList />
</header>
</div>
</TodoContext.Provider>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment