Last active
November 3, 2019 10:13
-
-
Save pubudu-ranasinghe/f2a4949d759377a833a65afa71baf575 to your computer and use it in GitHub Desktop.
react-context-eample-07
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 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