Last active
November 3, 2019 10:54
-
-
Save pubudu-ranasinghe/1062f79495c96d4139d497dc6715db8f to your computer and use it in GitHub Desktop.
react-context-example-12
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 { | |
useTodoContext, | |
addTodo, | |
removeTodo, | |
clearAll | |
} from "../contexts/TodoContext"; | |
export function NewItem() { | |
const [text, setText] = useState(""); | |
// Get the dispatcher from TodoContext | |
const { dispatch } = useTodoContext(); | |
// Dispatch addTodo action when adding a new item | |
return ( | |
<div className="Item"> | |
<input | |
type="text" | |
placeholder="New Task" | |
value={text} | |
onChange={e => setText(e.target.value)} | |
></input> | |
<button onClick={() => dispatch(addTodo(text))}>Add</button> | |
</div> | |
); | |
} | |
export function ItemList() { | |
const { items, dispatch } = useTodoContext(); | |
return ( | |
<> | |
{items.map((item, i) => ( | |
<Item text={item} index={i} key={i} dispatch={dispatch} /> | |
))} | |
{items.length > 0 && ( | |
<p | |
style={{ fontSize: "15px", cursor: "pointer" }} | |
onClick={() => dispatch(clearAll())} | |
> | |
Clear All | |
</p> | |
)} | |
</> | |
); | |
} | |
export function Item({ text, index, dispatch }) { | |
return ( | |
<div className="Item"> | |
{index + 1} {text} | |
<span onClick={() => dispatch(removeTodo(index))}>Done</span> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment