Lesson 1.3

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.

What you'll learn
  • 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
1

The Definition of a Component

Let's start with the basics. When you write a React component, what are you actually creating?

The Question

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

2

Variables and Interpolation

JSX allows us to mix JavaScript logic directly into our markup. But syntax matters.

The Scenario

You have a variable const label = "Submit";. How do you display this inside a button?

Option A

jsx
// Option A
<button>{{ label }}</button>

Option B

jsx
// Option B
<button>{ label }</button>

Option C

jsx
// Option C
<button>${ label }</button>
3

Rendering "Nothing"

Sometimes you want a component to hide itself completely.

The Statement

To render no UI, you can simply return any "falsy" JavaScript value.

True or False?

True

False

4

Conditional Rendering Logic

Newcomers often look for directives like v-if (Vue) or *ngIf (Angular) inside JSX.

The Question

Does JSX have a built-in r-if or if attribute for conditional rendering?

Yes

No

5

The "Adjacent Elements" Error

Analyze the following code snippet. It looks innocent enough, but it will crash your app.

jsx
function Layout() {
  return (
    <Sidebar />
    <MainContent />
  );
}
What is wrong here?

Components must be wrapped in a parent element or Fragment

Components cannot be PascalCase

Nothing is wrong

6

Lists and Keys

Rendering arrays is a daily task in React. Look at the code below:

jsx
const products = [
  { id: 101, name: 'Laptop' },
  { id: 102, name: 'Mouse' }
];

// Which render method is valid?

A

jsx
{products.forEach(p => <li>{p.name}</li>)}

B

jsx
{products.map(p => <li>{p.name}</li>)}

C

jsx
{products.map(p => <li key={p.id}>{p.name}</li>)}
7

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.

What is wrong with this component?
jsx
function ProfileCard() {
  return 
    <div className="card">
      <h1>User Name</h1>
    </div>
}
8

Attributes and Self-Closing Tags

Finally, let's look at syntax specific to HTML-to-JSX conversion.

Spot the errors in this snippet:
jsx
function SearchBar() {
  return (
    <div class="search-container">
      <label>Search:</label>
      <input type="text" name="query">
    </div>
  )
}