Why does this React component render as empty?
Code with error
Corrected code
Explanation
I’ve been bitten by this one more times than I care to admit. This error is especially devious because there’s no helpful syntax error. The syntax is perfectly valid, but it doesn’t have the desired result. The short explanation: the error code is not returning anything.
A brief detour for arrow functions
Arrow function expressions with implicit returns present some of the most confusing syntax in JavaScript.
Implicit returns are a shortcut notation for arrow functions. If the arrow (=>
) is followed by an expression that’s not surrounded by curly braces ({ }
), then the function will return that expression. This leads to wonderfully concise syntax. For example:
implicit return
However, if curly braces ({ }
) surround the function body, then there’s no return implied. An arrow function body surrounded by curly braces is called a “block body.” For example:
no return
This syntax is concise, sure, but also confusing. 😬 In this case, there’s no implicit return, and also no return
statement in the block body. So doNothing
returns undefined
(which is JavaScript’s behavior when there’s no return value provided ).
To return a value when using a block body (that is, a body surrounded by curly braces), you need an explicit return
statement:
explicit return
Back to the original Code Check
In the case of the React function in the Code Check, the error case is like the “no return” example: the code is set off by curly braces ({ }
) but there’s no explicit return
statement. The function returns undefined
, which is the equivalent of not returning any JSX. From the React docs on conditional rendering :
React considers false
as a “hole” in the JSX tree, just like null
or undefined
, and doesn’t render anything in its place.
By surrounding the JSX with parentheses (( )
) instead, the JSX becomes a multi-line expression, which the arrow function implicitly returns.
Alternative error / solution
Since I tend to use the function
syntax for my React components, this is usually how I get myself in trouble:
Code with error
Corrected code
The React function in the error case is a “no return” situation (the function includes JSX — but the JSX isn’t being returned). An explicit return
statement fixes the issue.