By now, you’re probably fairly comfortable with creating elements with React.createElement()
. You know that when you pass a children
argument, it will be rendered inside the created element — as its children.
But what happens when you create a component element with children
?
You may know the answer already! Have a little think about it, and check your answer below once you’re ready.
The third and subsqeuent arguments to React.createElement()
are always added to the props
as children
— regardless of the type.
So if you create an element with a custom type and children, you can access those children on its props
.
In fact, these two createElement
calls are equivalent:
let a = createElement(
AnyType,
{
children: x
}
)
let b = createElement(
AnyType,
{},
x
)
React components are functions that accept a props
argument, and return an element.
That element can come from anywhere — including props
.
For example, if you were feeling particularly unproductive, you could create a component that does nothing but return its children
prop.
One common use case for the children
props is layout components, i.e. components that wrap their children
in a styled container.
For example, you could create a component that centers its children on the screen, using flexbox and absolute positioning, solving one of the hardest problems in computer science once and for all!
ContactList
componentLet’s create a component to hold the top-level styles and markup for your contact list.
I’ve provided a set of starter styles in styles.css
, along with comments explaining where they go. I’ve also provided a Contact
component, based on the exercise from the previous lesson.
The starting code renders a ContactList
element, but the component is missing. It’s up to you to create the component.
Once complete, all of your elements should be encapsulated within one of the two components. You’re code will be modular - as God and the Unix designers intended!
The starting code uses Array.prototype.map
and spread syntax to build an array of ContactItem
elements.
You can read more on these here: