Skip to content

Instantly share code, notes, and snippets.

@pubudu-ranasinghe
Last active November 3, 2019 10:13
Show Gist options
  • Save pubudu-ranasinghe/f2a4949d759377a833a65afa71baf575 to your computer and use it in GitHub Desktop.
Save pubudu-ranasinghe/f2a4949d759377a833a65afa71baf575 to your computer and use it in GitHub Desktop.
react-context-eample-07
import React, { useState } from "react";
import TodoContext from "../contexts/TodoContext";
export function NewItem() {
const [text, setText] = useState("");
return (
<TodoContext.Consumer>
{values => (
<div className="Item">
<input
type="text"
placeholder="New Task"
value={text}
onChange={e => setText(e.target.value)}
></input>
<button onClick={() => values.add(text)}>Add</button>
</div>
)}
</TodoContext.Consumer>
);
}
export function ItemList() {
// Here we consume the values from TodoContext using the TodoContext Consumer
return (
<TodoContext.Consumer>
{values =>
values.items.map((item, i) => (
<Item text={item} index={i} key={i} remove={values.remove} />
))
}
</TodoContext.Consumer>
);
}
export function Item({ text, index, remove }) {
return (
<div className="Item">
{index + 1} {text}
<span onClick={() => remove(index)}>Done</span>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment