Without JSX, it would be as follows. Note that we're only passing in two arguments: the element type
and a props
object.
React.createElement("div", {
className: "App",
children: React.createElement("h1", {
className: "App-title",
children: "Hello, World!",
}),
});
Either way, the resulting virtual DOM node is the same.
<Item>
componentLet's start with our <Item>
component. We'll use destructuring assignment to assign a default value of false
to the .done
prop, and rest syntax so we can access the rest of the props via the props
object as normal.
Note that we're nesting the .children
prop inside the <span>
element. This lets us nest whatever text we want inside the <Item>
component instance, and it will be available via the .children
prop.
function Item({ done = false, ...props }) {
const [checked, setChecked] = useState(done);
function handleChange(event) {
setChecked(event.target.checked);
}
return (
<li className="Item">
<label>
<input
className="Item-input"
type="checkbox"
checked={checked}
onChange={handleChange}
/>
<span className="Item-label">{props.children}</span>
</label>
</li>
);
}
We haven't created our <List>
component yet, but we can still nest our <Item>
component within a regular <ul>
or <ol>
element. This is one of the benefits of composition; it makes it easy to reuse our code in different ways!
<ul>
<Item done={true}>Walk dogs</Item>
<Item>Buy groceries</Item>
<Item>Work out</Item>
</ul>
<List>
componentOur <List>
component will accept a .name
prop which we'll use as the text content for an <h2>
element.
We'll nest the .children
prop inside a <ul>
element. This means that when we nest instances of the <Item>
component inside an instance of the <List>
component, they'll become children of the <ul>
element.
function List(props) {
return (
<article className="List">
<header>
<h2>{props.name}</h2>
</header>
<ul role="list">{props.children}</ul>
</article>
);
}
With our <List>
component in place, we can nest instances of our <Item>
component. They'll be available to the instance of the <List>
component via its .children
prop:
<List name="To Do">
<Item done={true}>Walk dogs</Item>
<Item>Buy groceries</Item>
<Item>Work out</Item>
</List>
Composition is a fundamental concept in object-oriented programming (OOP) and a powerful way to reuse code between React components. We achieve composition in React using the special .children
prop.