React tricks
You now know the core building blocks: components, props, and state. But there are a few essential patterns you'll use in almost every React project.
This lesson covers conditional rendering, rendering lists with .map(), the children prop, and fragments.
1️⃣ Conditional rendering
Sometimes you want to show something on screen only when a certain condition is true.
For instance, a tooltip that appears on hover. Or perhaps a warning that shows when data is missing. A chart that only renders once the data has loaded.
→ logical AND operator
In React, you can do this with plain JavaScript. The most common pattern uses the "logical AND" operator (&&) that looks like this:
{isVisible && <Circle />}This reads: "if isVisible is true, render <Circle />. Otherwise, render nothing."
→ ternary operator
Sometimes you need to choose between two things, like rendering something in red under certain conditions, and in blue otherwise. In this case, you probably want to use a ternary operator:
{isRed ? <RedCircle /> : <BlueCircle />}Here is a live example of those 2 very useful patterns. Click the buttons to see them in action and take a moment to understand the code!
import { useState } from "react"; export default function App() { const [showCircle, setShowCircle] = useState(true); const [isRed, setIsRed] = useState(false); return ( <div> <div style={{ display: "flex", gap: 8, marginBottom: 16 }}> <button onClick={() => setShowCircle(!showCircle)}> {showCircle ? "Hide" : "Show"} circle </button> <button onClick={() => setIsRed(!isRed)}> Switch to {isRed ? "blue" : "red"} </button> </div> {showCircle && ( <div style={{ width: 100, height: 100, borderRadius: "50%", backgroundColor: isRed ? "tomato" : "dodgerblue", }} /> )} </div> ); }
Toggle visibility with &&, switch color with a ternary.
You probably don't realize it yet, but writing code like this is super convenient! There is no special API, no complex if/else directive in JavaScript decoupled from the HTML syntax. The JavaScript expressions are inside your JSX and it makes it very straightforward to write rendering logic.
2️⃣ Rendering lists
In data visualization, you rarely know in advance how many elements to draw. You have an array of data points, and you need to render one element per item.
In React, you do this with .map() — the array method that transforms each item into a piece of JSX:
const colors = ["tomato", "dodgerblue", "gold"];
// Inside JSX:
{colors.map((color, i) => (
<Circle key={i} color={color} />
))}Each item in the array becomes a component. The key prop is required — it helps React identify which items have changed when the list updates. Use a unique id if you have one, or the index as a fallback.
Oh no! 😱
It seems like you haven't enrolled in the course yet!
Join many other students today and learn how to create bespoke, interactive graphs with d3.js and React!
Enrollment is currently closed. Join the waitlist to be notified when doors reopen:
Or Login