惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Spread Privacy
Spread Privacy
K
Kaspersky official blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Forbes - Security
Forbes - Security
Hacker News - Newest:
Hacker News - Newest: "LLM"
The Last Watchdog
The Last Watchdog
SecWiki News
SecWiki News
Attack and Defense Labs
Attack and Defense Labs
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
S
Secure Thoughts
WordPress大学
WordPress大学
Microsoft Security Blog
Microsoft Security Blog
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
Security Latest
Security Latest
TaoSecurity Blog
TaoSecurity Blog
Cyberwarzone
Cyberwarzone
S
SegmentFault 最新的问题
Cloudbric
Cloudbric
aimingoo的专栏
aimingoo的专栏
S
Schneier on Security
N
Netflix TechBlog - Medium
MyScale Blog
MyScale Blog
T
The Blog of Author Tim Ferriss
H
Hacker News: Front Page
C
Cybersecurity and Infrastructure Security Agency CISA
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
AWS News Blog
AWS News Blog
AI
AI
G
GRAHAM CLULEY
IT之家
IT之家
P
Privacy & Cybersecurity Law Blog
L
Lohrmann on Cybersecurity
Last Week in AI
Last Week in AI
D
Docker
Recent Announcements
Recent Announcements
O
OpenAI News
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
S
Security @ Cisco Blogs
T
Troy Hunt's Blog
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
A
About on SuperTechFans
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
N
News and Events Feed by Topic

Kent C. Dodds Blog

Implementing Hybrid Semantic + Lexical Search Simplifying Containers with Cloudflare Sandboxes Migrating to Workspaces and Nx Offloading FFmpeg with Cloudflare Building Semantic Search on my Content Helping YOU ask ME questions with AI How I used Cursor to Migrate Frameworks The Dow's Start on the Covenant Path 2025 in Review The next chapter: EpicAI.pro AI is taking your job How I increased my visibility Launching Epic Web 2023 in Review Stop Being a Junior RSC with Dan Abramov and Joe Savona Live Stream Fixing a Memory Leak in a Production Node.js App 2022 in Review My Car Accident I Migrated from a Postgres Cluster to Distributed SQLite with LiteFS I'm building EpicWeb.dev A review of my time at Remix Remix: The Yang to React's Yin How I help you build better websites Why I Love Remix The State Initializer Pattern How to React ⚛️ Get a catch block error message with TypeScript Building an awesome image loading experience How Remix makes CSS clashes predictable Introducing the new kentcdodds.com How I built a modern website in 2021 How to use React Context effectively Static vs Unit vs Integration vs E2E Testing for Frontend Apps The Testing Trophy and Testing Classifications Array reduce vs chaining vs for loop Don't Solve Problems, Eliminate Them Super Simple Start to Remix Super Simple Start to ESModules in Node.js JavaScript Pass By Value Function Parameters How to write a Constrained Identity Function (CIF) in TypeScript How to optimize your context value How to write a React Component in TypeScript TypeScript Function Syntaxes Listify a JavaScript Array Build vs Buy: Component Libraries edition Using fetch with TypeScript Wrapping React.useState with TypeScript Define function overload types with TypeScript 2020 in Review Business and Engineering alignment Hi, thanks for reaching out to me 👋 useEffect vs useLayoutEffect Super simple start to Firebase functions Super simple start to Netlify functions Super Simple Start to css variables Favor Progress Over Pride in Open Source Testing Implementation Details How getting into Open Source has been awesome for me useState lazy initialization and function updates Application State Management with React Use react-error-boundary to handle errors in React JavaScript to Know for React How I structure Express apps What open source project should I contribute to? When I follow TDD AHA Programming 💡 How I Record Educational Videos Should I write a test or fix a bug? Stop mocking fetch Intentional Career Building Improve test error messages of your abstractions Tracing user interactions with React Eliminate an entire category of bugs with a few simple tools Common mistakes with React Testing Library Super Simple Start to React Stop using client-side route redirects The State Reducer Pattern with React Hooks Function forms Replace axios with a simple custom fetch wrapper How to test custom React hooks React Production Performance Monitoring Should I useState or useReducer? Stop using isLoading booleans Make Your Test Fail Make your own DevTools An Argument for Automation Fix the "not wrapped in act(...)" warning Super Simple Start to ESModules in the Browser Implementing a simple state machine library in JavaScript 2010s Decade in Review Why users care about how you write code Why I avoid nesting closures Don't call a React function component Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode How to add testing to an existing project Profile a React App for Performance
Use ternaries rather than && in JSX
2020-07-27 · via Kent C. Dodds Blog

What's wrong with this code?

function ContactList({ contacts }) {
	return (
		<div>
			<ul>
				{contacts.length &&
					contacts.map((contact) => (
						<li key={contact.id}>
							{contact.firstName} {contact.lastName}
						</li>
					))}
			</ul>
		</div>
	)
}

Not sure? Let me ask you another question. What would happen with the above code if contacts was []? That's right! You'd render 0!

I shipped this mistake to production at PayPal once. No joke. It was on this page:

PayPal page with contacts

When a user came with no contacts, this is what they saw:

PayPal page with 0 instead of contacts

Yeah, that was not fun... Why is that? Because when JavaScript evaluates 0 && anything the result will always be 0 because 0 is falsy, so it doesn't evaluate the right side of the &&.

The solution? Use a ternary to be explicit about what you want rendered in the falsy case. In our case, it was nothing (so using null is perfect):

function ContactList({ contacts }) {
	return (
		<div>
			<ul>
				{contacts.length
					? contacts.map((contact) => (
							<li key={contact.id}>
								{contact.firstName} {contact.lastName}
							</li>
						))
					: null}
			</ul>
		</div>
	)
}

What about this code? What's wrong here?

function Error({ error }) {
	return error && <div className="fancy-error">{error.message}</div>
}

Not sure? What if error is undefined? If that's the case, you'll get the following error:

Uncaught Error: Error(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

Or, in production, you might get this:

react-dom.production.min.js:13 Uncaught Invariant Violation: Minified React error #152; visit https://reactjs.org/docs/error-decoder.html?invariant=152&args[]=f for the full message or use the non-minified dev environment for full errors and additional helpful warnings.

The problem here is that undefined && anything will always evaluate to undefined.

So what gives?

Really, the problem in both of these cases is we're using && to do conditional rendering. Said differently, we're using && to do conditional argument passing. Remember, JSX is a simple syntactic abstraction over calling React.createElement. So it'd be like trying to write this:

function throwTheCandy(candyNames) {
	for (const candyName of candyNames) {
		throwCandy(candyName)
	}
}

throwTheCandy(candies.length && candies.map((c) => c.name))

That wouldn't make any sense right? We've got our types all messed up. The reason React allows you to do this though is because rendering 0 is valid.

Luckily, TypeScript can help you avoid the second example of accidentally returning undefined. But on top of that layer of protection, how about we be more explicit about our intentions. If you want to do something conditionally, don't abuse the logical AND operator (&&).

If you'd like an extra layer of protection, you can also use eslint-plugin-react's jsx-no-leaked-render rule to help catch cases where && might accidentally leak something like 0 into your render output.

It actually seems counter-intuitive because we often use && in an if condition to say: if both of these values are truthy, then do this thing, otherwise don't. Unfortunately for our use-case, the && operator also has this "feature" where if both values aren't truthy, it returns the value of the falsy one:

0 && true // 0
true && 0 // 0
false && true // false
true && '' // ''

Use actual branching syntax

So I strongly suggest that rather than abusing && (or || for that matter) in your JSX, you use actual branching syntax features, like ternaries (condition ? trueConsequent : falseConsequent) or even if statements (and in the future, maybe even do expressions).

I'm personally a fan of ternaries, but if you'd prefer if statements, that's cool too. Here's how I'd do the contacts thing with if statements:

function ContactList({ contacts }) {
	let contactsElements = null
	if (contacts.length) {
		contactsElements = contacts.map((contact) => (
			<li key={contact.id}>
				{contact.firstName} {contact.lastName}
			</li>
		))
	}

	return (
		<div>
			<ul>{contactsElements}</ul>
		</div>
	)
}

Personally, I think the ternary is more readable (if you disagree, remember that "readable" is subjective and the readability of something has much more to do with familiarity than anything else). Whatever you do, you do you, just don't do bugs.

Another benefit of using actual branching syntax is that test coverage tools can detect and indicate when your tests are not covering one of the branches.

Conclusion

I'm well aware that we could've solved the contact problem by using !!contacts.length && ... or contacts.length > 0 && ... or even Boolean(contacts.length) && ..., but I still prefer not abusing the logical AND operator for rendering. I prefer being explicit by using a ternary.

To finish strong, if I had to write both of these components today, here's how I'd write them:

function ContactList({ contacts }) {
	return (
		<div>
			<ul>
				{contacts.length
					? contacts.map((contact) => (
							<li key={contact.id}>
								{contact.firstName} {contact.lastName}
							</li>
						))
					: null}
			</ul>
		</div>
	)
}
function Error({ error }) {
	return error ? <div className="fancy-error">{error.message}</div> : null
}

Good luck!