Composing Components3:19 with Guil Hernandez
When a component contains another component, it's called composition. Composing components is a core principle in React. You'll usually have parent components with one or many child components. This gives the parent component the ability to control how its child components are rendered.
How did it go? 0:00 In the previous video, I challenged you to create a counter 0:00 component using the counter code inside the Player component. 0:04 Now I'll show you my solution. 0:08 I'll start by creating a new function named Counter. 0:10 Inside the function, I'll add the return keyword, 0:18 followed by a set of parentheses to hold my JSX. 0:22 Then I'll cut the div with className="counter" out of the Player 0:27 component, and paste it inside the parentheses of the new Counter function. 0:31 Now that the Counter component is complete, 0:43 we need a way to display it inside the Player component. 0:46 React components can make use of, or refer, to other React components. 0:50 For example, you can render the Counter component within the Player 0:55 component by just using the Counter tag inside Player's return statement. 1:00 When a component contains another component like this, 1:10 it's called composition. 1:13 Composing components is a core principle in React. 1:15 It'll usually have parent components like Player with one or many child components. 1:19 This gives the parent component the ability to control how 1:25 its child components are rendered. 1:28 You'll learn a whole lot more about that in the next stage. 1:30 Typically, React applications have a single top level component that 1:33 wraps the entire application and composes all the main components together. 1:37 So I'll create a new function component named App. 1:41 This component will return a div with the class scoreboard. 1:55 Inside the div, we'll render our header component using a self-closing Header tag. 2:07 To display the list of players, 2:14 I'll first add a JSX comment to indicate the start of our Players list. 2:17 Then I'll render one Player component for now, using the Player tag. 2:25 ReactDOM.render usually renders your top level element into the DOM. 2:32 So let's pass our App component to ReactDOM.render using its JSX tag. 2:37 I'll save app.js. 2:45 Once I refresh the browser, 2:47 we see that our entire application is now mounted into the DOM. 2:49 There are no hard and 2:54 fast rules about how to divide your components in a React application. 2:55 Much like writing any other code, how and 2:59 when to break it down can be a matter of personal or team preference. 3:01 Having a few large and unwieldy components has its pros and cons. 3:05 Having too many tiny components also has its pros and cons. 3:09 So the key is to strike a balance. 3:12 Remember, you can restructure your code as you go, 3:14 if you feel like it's not divided well. 3:16
You need to sign up for Treehouse in order to download course files.Sign up