Skip to content

Commit f28e180

Browse files
Added the contextAPI and useContext
1 parent ec5e527 commit f28e180

File tree

2 files changed

+54
-2
lines changed

2 files changed

+54
-2
lines changed

src/App.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,10 @@ import "./index.css";
3232
// import Index from "./advance_react/useReducer";
3333

3434
// ! /* propDrilling */
35-
import PropDrilling from "./advance_react/prop_drilling/prop_drilling";
35+
// import PropDrilling from "./advance_react/prop_drilling/prop_drilling";
36+
37+
// ! /* ContextAPI/useContext */
38+
import ContextAPI from "./advance_react/useContext/useContext";
3639

3740
function App() {
3841
return (
@@ -67,7 +70,10 @@ function App() {
6770
{/* <Index /> */}
6871

6972
{/* propDrilling */}
70-
<PropDrilling />
73+
{/* <PropDrilling /> */}
74+
75+
{/* contextAPI/useContext */}
76+
<ContextAPI />
7177
</div>
7278
</React.Fragment>
7379
);
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import React, { useState, useContext } from "react";
2+
import { data } from "../../data";
3+
4+
const PeopleContext = React.createContext();
5+
6+
function ContextAPI() {
7+
const [people, setPeople] = useState(data);
8+
9+
const removeItem = (id) => {
10+
setPeople((people) => {
11+
return people.filter((person) => person.id !== id);
12+
});
13+
};
14+
15+
return (
16+
<PeopleContext.Provider value={{ removeItem, people }}>
17+
<h1>ContextAPI/useContext</h1>
18+
<List people={people} />
19+
</PeopleContext.Provider>
20+
);
21+
}
22+
23+
function List({ people }) {
24+
const peopleData = useContext(PeopleContext);
25+
return (
26+
<>
27+
{peopleData.people.map((person) => {
28+
return <SinglePerson key={person.id} {...person} />;
29+
})}
30+
</>
31+
);
32+
}
33+
34+
function SinglePerson({ id, name }) {
35+
const { removeItem } = useContext(PeopleContext);
36+
return (
37+
<div className="item">
38+
<p>{name}</p>
39+
<button type="button" onClick={() => removeItem(id)}>
40+
romove
41+
</button>
42+
</div>
43+
);
44+
}
45+
46+
export default ContextAPI;

0 commit comments

Comments
 (0)