- Components can use other components in their output
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return (
<div>
<Welcome name="Becky" />
<Welcome name="Jim" />
<Welcome name="Edwardo" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
- Note that components that return multi-line JSX must use
()
to surround the JSX, and there must always be one parent element (use <>
to create a fragment when no element is wanted)
function App() {
// Wrong! Missing single parent element
return (
<Welcome name="Becky" />
<Welcome name="Jim" />
<Welcome name="Edwardo" />
);
}
function App() {
// Create a fragment instead
return (
<>
<Welcome name="Becky" />
<Welcome name="Jim" />
<Welcome name="Edwardo" />
</>
);
}
- New React apps typically have a single
App
component at the top and then child components that might each have their own children
- Example
Comment
component has a UserInfo
child component, which has an Avatar
child component
function Avatar(props) {
return (
<img className="Avatar"
src={props.user.avatarUrl}
alt={props.user.name}
/>
);
}
function UserInfo(props) {
return (
<div className="UserInfo">
<Avatar user={props.user} />
<div className="UserInfo-name">
{props.user.name}
</div>
</div>
);
}
function Comment(props) {
return (
<div className="Comment">
<UserInfo user={props.author} />
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}