Frontend Components and React Basics
Build component based UIs with React, manage state, effects, and routing, and connect to Flask APIs.
Content
JSX syntax essentials
Versions:
Watch & Learn
AI-discovered learning video
Sign in to watch the learning video for this topic.
JSX Syntax Essentials — How JSX Lets You Write HTML Inside JavaScript
"JSX is not HTML. It's closer to JavaScript dressed up in HTML cosplay." — probably your friendly TA
You just learned how to fetch JSON from an API, parse it, and pump it into your app asynchronously. Great! Now the next trick: actually render that JSON to the page in a way humans (and recruiters) can admire. Enter JSX — the way React lets you write HTML-like syntax directly inside JavaScript functions.
This guide covers the JSX syntax essentials you need to convert API data into clean, readable, and bug-resistant UI. Think of it as the bridge between the raw JSON you fetch and the shiny components users click.
What is JSX and why should I care?
- JSX (JavaScript XML) is a syntax extension for JavaScript that looks like HTML but compiles to plain JavaScript calls (React.createElement under the hood).
- It’s syntactic sugar — nicer to write and read than verbose function calls.
- Using JSX makes mapping fetched data to UI intuitive: you can inline expressions, loop, and conditionally render elements.
This is the moment where the concept finally clicks: you don’t need to switch mental gears between "HTML" and "JS" — JSX keeps them in the same file, which is delightfully efficient and sometimes just chaos.
JSX Rules You’ll Break If You Don’t Know Them
1) JSX expressions live in curly braces
Use curly braces to evaluate JavaScript expressions inside JSX.
// inside a component
return (
<div>
<h1>{user.name}</h1>
<p>{user.age > 18 ? "Adult" : "Minor"}</p>
</div>
);
- You can put any expression (not statements) in { } — arithmetic, function calls, ternaries, array maps.
2) One parent element per return
JSX must return a single root. Use a wrapper element or a fragment.
// Using a fragment
return (
<>
<Header />
<Main />
</>
);
3) className, htmlFor, and other camelCase attributes
JSX uses JS property names, not HTML attributes.
- Use
classNameinstead ofclass - Use
htmlForinstead offor - Inline styles are objects:
style={{ backgroundColor: 'red' }}
<button className="btn" style={{ padding: 8 }}>Click</button>
<label htmlFor="email">Email</label>
4) Self-closing tags
Even if the HTML could be empty, JSX insists on self-closing.
<input />
<MyComponent />
5) Comments inside JSX
Use {/* comment */} syntax inside JSX.
return (
<div>
{/* This comment appears inside JSX */}
</div>
);
6) No statements inside curly braces
You can write expressions but not statements. So no if(...) {} directly — use ternary or &&.
{/* OK */}
{items.length ? <List /> : <Empty />}
{/* Also OK */}
{isLoaded && <Content />}
7) Keys when rendering lists
When mapping arrays to elements, add a stable key prop — ideally a unique id.
{posts.map(post => (
<Article key={post.id} post={post} />
))}
Why keys? They help React diff and update lists efficiently. Using an index as key is okay sometimes, but prefer unique ids for reordering safety.
Practical Example: Render API-fetched JSON with JSX
Remember the fetch logic from the previous unit? Combine it with JSX to render a list:
function PostsList() {
const [posts, setPosts] = React.useState([]);
const [loading, setLoading] = React.useState(true);
React.useEffect(() => {
fetch('/api/posts')
.then(res => res.json())
.then(data => {
setPosts(data);
setLoading(false);
});
}, []);
if (loading) return <p>Loading posts…</p>;
return (
<ul>
{posts.map(post => (
<li key={post.id}>
<h3>{post.title}</h3>
<p>{post.excerpt}</p>
</li>
))}
</ul>
);
}
Notes:
- We used
{posts.map(...)}to turn JSON into JSX list items. key={post.id}prevents re-render bugs.- Conditional return
if (loading)demonstrates early returns instead of embedding statements inside JSX.
Extra Patterns and Gotchas
- Dangerous HTML:
dangerouslySetInnerHTMLexists if you must insert raw HTML, but sanitize first. - Fragments avoid unnecessary DOM wrappers:
<>...</>vs<div>...</div>. - Event handlers are camelCase and receive synthetic events:
onClick={handleClick}.
<button onClick={() => alert('hi')}>Say hi</button>
- Remember JSX isn't required — you can write
React.createElement— but JSX is far more readable.
Quick Comparison: JSX vs Vanilla createElement
// JSX
<div className="card">Hello</div>
// Compiles to roughly:
React.createElement('div', { className: 'card' }, 'Hello');
This transformation is handled by Babel during build. So when you write JSX, the browser still gets plain JS.
Closing: Key Takeaways
- JSX looks like HTML but is JavaScript — use curly braces for expressions.
- Single root, use keys, use className, and stay expression-only inside { }.
- JSX makes mapping fetched JSON into UI natural: combine
map,key, and fragments to render API data cleanly.
Remember: once you master JSX, rendering dynamic data from your async calls becomes straightforward and satisfying — like finishing a complex fetch and watching your UI bloom into life. It’s not magic, it’s syntax that saves you from writing a million nested createElement calls.
Happy rendering. Now go map those arrays like you mean it.
Final micro-mantra
"JSX is JavaScript with a fancy outfit. Treat it like JS, but enjoy the outfit."
Comments (0)
Please sign in to leave a comment.
No comments yet. Be the first to comment!