Building Complex UI with JSX
In the previous chapter, we explored the basics of JSX. Now, let's dive deeper and learn how to create more complex JSX elements.
The Rule of a Single Parent Element
One important rule when working with nested JSX is that it must return a single parent element. This parent element wraps all the other levels of nested elements. This rule ensures that React can properly render and manage the structure of your JSX. Here's a practical example to illustrate this rule:
Valid JSX:
<div>
<h1>Welcome to My Website</h1>
<p>Explore amazing content:</p>
<ul>
<li>Article 1</li>
<li>Article 2</li>
<li>Article 3</li>
</ul>
</div>
Invalid JSX (Won't Transpile):
<h1>Welcome to My Website</h1>
<p>Explore amazing content:</p>
<ul>
<li>Article 1</li>
<li>Article 2</li>
<li>Article 3</li>
</ul>
Note
When rendering multiple elements like this, we can wrap them all in parentheses
()
for clarity, but it's not strictly required. Also, remember that this concept applies when we return JSX elements in React components.
Example
const JSX = (
<div>
<h1>Welcome to My Website</h1>
<p>Explore amazing content:</p>
<ul>
<li>Article 1</li>
<li>Article 2</li>
<li>Article 3</li>
</ul>
</div>
);
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Awesome!
Completion rate improved to 2.17
Building Complex UI with JSX
Svep för att visa menyn
In the previous chapter, we explored the basics of JSX. Now, let's dive deeper and learn how to create more complex JSX elements.
The Rule of a Single Parent Element
One important rule when working with nested JSX is that it must return a single parent element. This parent element wraps all the other levels of nested elements. This rule ensures that React can properly render and manage the structure of your JSX. Here's a practical example to illustrate this rule:
Valid JSX:
<div>
<h1>Welcome to My Website</h1>
<p>Explore amazing content:</p>
<ul>
<li>Article 1</li>
<li>Article 2</li>
<li>Article 3</li>
</ul>
</div>
Invalid JSX (Won't Transpile):
<h1>Welcome to My Website</h1>
<p>Explore amazing content:</p>
<ul>
<li>Article 1</li>
<li>Article 2</li>
<li>Article 3</li>
</ul>
Note
When rendering multiple elements like this, we can wrap them all in parentheses
()
for clarity, but it's not strictly required. Also, remember that this concept applies when we return JSX elements in React components.
Example
const JSX = (
<div>
<h1>Welcome to My Website</h1>
<p>Explore amazing content:</p>
<ul>
<li>Article 1</li>
<li>Article 2</li>
<li>Article 3</li>
</ul>
</div>
);
Tack för dina kommentarer!