Create Context2:49 with Guil Hernandez
In this video, we'll initialize a new context using
createContext(), and implement the Context API into our project.
Let's start by creating a new folder named Context inside the components folder. 0:00 In the Context folder, create a new file named index.js. 0:05 This file structure naming isn't required, I'm just doing it for organization and 0:10 maintenance reasons. 0:13 In index.js, let's first import React with import React from 'react'. 0:15 And now we'll initialize a new context using the create context method. 0:23 We'll assign the context to a variable, so let's declare a variable named 0:28 ScoreboardContext, and set it to React.createContext. 0:33 This is going to setup our provider and consumer. 0:41 ScoreboardContext now returns an object with Consumer and 0:45 Provider properties that are also objects. 0:49 Next, we'll assign the provider to a variable named Provider, 0:52 with const Provider = ScoreboardContext.Provider. 0:56 And store the consumer in a variable named Consumer, with const Consumer 1:02 = ScoreboardContext.Consumer. 1:08 Next, we need to export the provider and consumer so 1:13 that we can import them into other modules and use them in our components. 1:16 So I'll add the export keyword just before each const declaration. 1:20 And now we're all setup to use context in our app. 1:27 We'll make use of the Provider and 1:29 the parent app component where we have our state. 1:31 So in App.js, I'll use a named import to import just the Provider 1:34 from the index.js file located inside the Context folder. 1:40 You don't need to include index.js in the import path. 1:48 When resolving the import path to the context directory, 1:52 know that we'll look for an index.js file and load it. 1:55 So ./Context is really a path to Context/index.js. 1:58 Now, to provide the context to all children of app, 2:05 I'll wrap all the jsx and the return statement within Provider text. 2:09 If you have a look at the component tree in React Devtools, 2:21 you should see that a new component named Context.Provider, 2:25 is now the parent of the Header, PlayerList, and AddPlayerForm component. 2:28 All right, now that context is set and the provider is in place, in the next video, 2:34 we'll provide the players state to the entire app. 2:38 And setup the consumers that will subscribe or 2:42 connect to the provider in order to make use of the context. 2:45
You need to sign up for Treehouse in order to download course files.Sign up