- Home
- /
- Tutorials
- /
- React Tutorial
- /
- What a Component Can Return
Components and Props
What a Component Can Return
A component does not have to return an element. Returning
nullis how you say "render nothing here", and it is a normal, expected thing to do.
The allowed returns
Six valid components
jsx
const AnElement = () => <p>An element</p>
const AString = () => "A bare string"
const ANumber = () => 42
const AnArray = () => [<span key="a">one </span>, <span key="b">two</span>]
const AFragment = () => (
<>
<em>fragment child</em>{" "}
<em>and another</em>
</>
)
const Nothing = () => null
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(
<div>
<AnElement />
<p><AString /></p>
<p><ANumber /></p>
<p><AnArray /></p>
<p><AFragment /></p>
<p>Nothing renders between the brackets: [<Nothing />]</p>
</div>
)Note the key on the array items. Any time you return a list of elements React wants a stable identity for each one - the lists chapter explains why in detail.
Returning null on purpose
A component that decides it has nothing to show returns null. This is cleaner than making every caller wrap it in a condition, because the rule lives with the component that owns it.
The component hides itself
jsx
function Warning({ count }) {
// Nothing to warn about, so render nothing.
if (count === 0) return null
return (
<p style={{ color: "#b91c1c" }}>
{count} item{count === 1 ? "" : "s"} need attention
</p>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(
<div>
<Warning count={0} />
<Warning count={1} />
<Warning count={4} />
<p style={{ color: "#475569" }}>Only two warnings above — the first returned null.</p>
</div>
)Returning null is not the same as not rendering
The component still runs. Its hooks still run, its state is still kept, and React still has it in the tree - it simply produces no DOM. That distinction matters once you reach effects, because a component returning null can still be doing work.
What cannot be returned
- An object - React throws rather than guess how to display it.
- Two adjacent elements - a function returns one value; wrap them.
undefinedfrom a missing return - usually the semicolon bug from the JSX chapter, and it throws.
The distinction between null and undefined is worth holding on to: null means "deliberately nothing", and undefined almost always means you forgot to return.
Strings and numbers are elements too
Because a component may return a bare string, a component is not required to produce a tag. That is occasionally useful for formatting helpers - a Price component that returns formatted text, used inline inside a sentence, without introducing a span that CSS then has to work around.
It also explains why {someComponent()} and <SomeComponent /> are not interchangeable. The first is a plain function call whose result is inlined; the second creates an element React manages, with its own identity and its own state. Always use the tag.
