react-context-example-06
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, { 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