Skip to content

Commit

Permalink
useContext to access data from any child components
Browse files Browse the repository at this point in the history
  • Loading branch information
jessilyneh committed Mar 4, 2022
1 parent 10de4e8 commit 75a9b2c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 14 deletions.
18 changes: 15 additions & 3 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
import { useContext } from "react";
import "./App.css";
import { HeadachesContext } from "./index";

function App({ name }) {
function App() {
//any component that is part of the app, because its
//been wrapper in the provider, we can read the value of
//headache context just calling useContext
const { headaches } = useContext(HeadachesContext);
console.log(headaches); // a object headaches (4 elements)
return (
<div className="App">
<h1>Hello,{name}</h1>
<div>
<h1>Types of headaches</h1>
<ul>
{headaches.map((headache) => (
<li key={headache.id}>{headache.type}</li>
))}
</ul>
</div>
);
}
Expand Down
18 changes: 7 additions & 11 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,22 @@
import React, { createContext } from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";

export const TreesContext = createContext();
export const HeadachesContext = createContext();

const trees = [
//make all this data acessible to all app
const headaches = [
{ id: "1", type: "migraines" },
{ id: "2", type: "digestive problem" },
{ id: "3", type: "sinus headaches" },
{ id: "4", type: "tension" }
];
export default function App() {
return (
<div>
<h1>Types of headaches</h1>
</div>
);
}

// Pass data down to the child components
ReactDOM.render(
<TreesContext.Provider value={{ trees }}>
<HeadachesContext.Provider value={{ headaches }}>
<App />
</TreesContext.Provider>,
</HeadachesContext.Provider>,
document.getElementById("root")
);

0 comments on commit 75a9b2c

Please sign in to comment.