I remember the annoyance of having to debug functions with implicit returns. Because implicit returns must be used in conjunction with an expression, we can't just add another line to our arrow-function.
So imagine we made a mistake in the props we passed to our imaginary BlogPost
-component.
We misspelled content
:
// ...snip
return (
<BlogPost title="My first post" subtitle="hurray!" conten="lorem ipsum and stuff" />
)
// ...snip
And we render this component:
const BlogPost = props => (
<main>
<h2>{props.title}</h2>
<h3>{props.subtitle}</h3>
<p>{props.content}</p>
</main>
);
Now, why does the content of my blog-post not show up ๐คจ?
One option is to rewrite your component using an explicit return:
const BlogPost = props => {
console.log(props)
return ( // Ugh, I had to wrap the component it in curly's just to log the props
<main>
<h2>{props.title}</h2>
<h3>{props.subtitle}</h3>
<p>{props.content}</p>
</main>
);
}
Having to do this once or twice is not so bad. But when you have to constantly add curlies and returns (and remove them after), it starts to get tedious. One little trick to make this easier is to do this instead:
const BlogPost = props => console.log(props) || (
<div>
<h2>{props.title}</h2>
<h3>{props.subtitle}</h3>
<p>{props.content}</p>
</div>
);
The result of console.log
(or any of the console-methods really) is undefined. And as undefined is a falsey value, the right-side of the OR
-operator will be evaluated and the component will be rendered.
Note that you could also use the new nullish coalescing operator
for this:
const BlogPost = props => console.log(props) ?? (
<div>
<h2>{props.title}</h2>
<h3>{props.subtitle}</h3>
<p>{props.content}</p>
</div>
)
And so we can use short-circuiting to make debugging functions with implicit returns a bit less time-consuming.
Top comments (1)
Awesome