Nesting React Components
The power of React comes in it’s component-based nature. We can create and reuse components to build complex web interfaces. It’s kind of like building with Legos, but you get to create the blocks. Let’s build a few components that we will use to compose a blogging web page.
We’ll build this in CodePen- if you don’t know how to set up CodePen for React, check out this story.
First let’s start with a title component for our blog site:
const Heading = () => {
return (
<h1>My Blog</h1>
);
};
Then let’s put together the the blog section component:
const Blog = () => {
return (
<div>
<h2>Blog Title</h2>
<p>Blog Body</p>
</div>
);
};
Notice that we wrapped the h2 and p tags with a div tag. Remember that JSX compiles into a React.createElement function, and ReactDOM.render only accepts one React.createElement function. Wrapping the h2 and p tags ensures that we return one function when JSX is converted to JavaScript.
Now let’s nest those components to build our blogging web app:
const App = () => {
return(
<div>
<Heading />
<Blog />
<Blog />
<Blog />
</div>
);
};
Once again, notice how we wrapped our components in a div tag to ensure that JSX returns one React.createElement function.
Now let’s render our app to the DOM- add your root div to your HTML file:
<div id="root"></div>
And then call ReactDOM in your JS file to render your app:
ReactDOM.render(
<App />,
document.getElementById('root')
);
You should be seeing this in CodePen:
Let’s break down what is going on here:
Check out the CodePen here:
Next- let’s pass some data to our components.