Do You Know JSX Really?
Whether you are a beginner or a seasoned pro, it's easy to overlook the nuances of how JSX actually compiles and renders. Below are 8 concepts derived from common interview questions. Read through, test yourself, and see if you can spot the bugs in the new examples provided.
- •8 key JSX concepts derived from common interview questions
- •How JSX actually compiles and renders
- •Common bugs and pitfalls in JSX syntax
- •Practical examples and bug fixes
The Definition of a Component
Let's start with the basics. When you write a React component, what are you actually creating?
Which of the following best describes a React component?
A class that strictly renders HTML strings.
A function that returns a description of the UI
A template engine that compiles to Handlebars
Variables and Interpolation
JSX allows us to mix JavaScript logic directly into our markup. But syntax matters.
You have a variable const label = "Submit";. How do you display this inside a button?
Option A
// Option A
<button>{{ label }}</button>Option B
// Option B
<button>{ label }</button>Option C
// Option C
<button>${ label }</button>Rendering "Nothing"
Sometimes you want a component to hide itself completely.
To render no UI, you can simply return any "falsy" JavaScript value.
True or False?
True
False
Conditional Rendering Logic
Newcomers often look for directives like v-if (Vue) or *ngIf (Angular) inside JSX.
Does JSX have a built-in r-if or if attribute for conditional rendering?
Yes
No
The "Adjacent Elements" Error
Analyze the following code snippet. It looks innocent enough, but it will crash your app.
function Layout() {
return (
<Sidebar />
<MainContent />
);
}Components must be wrapped in a parent element or Fragment
Components cannot be PascalCase
Nothing is wrong
Lists and Keys
Rendering arrays is a daily task in React. Look at the code below:
const products = [
{ id: 101, name: 'Laptop' },
{ id: 102, name: 'Mouse' }
];
// Which render method is valid?A
{products.forEach(p => <li>{p.name}</li>)}B
{products.map(p => <li>{p.name}</li>)}C
{products.map(p => <li key={p.id}>{p.name}</li>)}The JavaScript "Return" Trap
JavaScript has a feature called Automatic Semicolon Insertion (ASI). It can break your JSX if you aren't careful with formatting.
function ProfileCard() {
return
<div className="card">
<h1>User Name</h1>
</div>
}Attributes and Self-Closing Tags
Finally, let's look at syntax specific to HTML-to-JSX conversion.
function SearchBar() {
return (
<div class="search-container">
<label>Search:</label>
<input type="text" name="query">
</div>
)
}