Undefined is not a Default
I love seeing React’s continued progress toward standard JavaScript.
We went from createClass
to class in 2014. Then from class to function in 2018. Every major change made a bigger and bigger bet on bone-stock JavaScript.
One API we needed for createClass
class components was defaultProps
. It let us use an appropriate fallback where a prop was required but not provided. This API made props available to all of the many lifecycle events.
Now — with Hooks — “lifecycle” functions happen inside the bodies of component functions. So we can lean on standard JavaScript to replace this API.
Undefined is not default
In our last lesson, we reassigned as (lowercase) to As
(uppercase) — when unpacking our props with destructuring assignment.
function Greeting({ as: As, name }) { … }
Unfortunately this component has a bug. What happens if we try to render it without providing the as prop? It throws an error; it can’t render undefined as a component.
Fortunately, we can declare a default when destructuring props:
function Greeting({ as: As = “div”, name }) { … }
Take it home
Take a minute to change the defaults and explore overriding them in this CodeSandbox.
Take it further by asking: is there a way in React that we could render this without any surrounding element? Hint: the answer has to do with what we’ve learned about arrays and React.