Skip to content

Instantly share code, notes, and snippets.

@pubudu-ranasinghe
Last active November 3, 2019 10:54
Show Gist options
  • Save pubudu-ranasinghe/1062f79495c96d4139d497dc6715db8f to your computer and use it in GitHub Desktop.
Save pubudu-ranasinghe/1062f79495c96d4139d497dc6715db8f to your computer and use it in GitHub Desktop.
react-context-example-12
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