Labs ICT
โญ Pro Login

JSX Basics

Writing HTML-like syntax in JavaScript.

JSX Basics

Ever wondered how you can write HTML-like code inside JavaScript? That's JSX - JavaScript XML. It's a syntax extension that lets you write HTML directly in your JavaScript files. Before React, mixing HTML and JS was a big no-no, but JSX makes it clean and intuitive.

Think of JSX as a bridge between JavaScript and HTML. It looks like HTML, but it's actually JavaScript under the hood. The browser doesn't understand JSX directly - Babel (which comes with Create React App) transforms it into regular JavaScript before it reaches the browser.

JSX Expressions

Here's the cool part - you can embed any JavaScript expression inside JSX using curly braces. Want to display a variable? Use curly braces. Want to calculate something? Curly braces! It's like having a window from JSX into your JavaScript world.

const name = "React Learner";
const element = <h1>Hello, {name}!</h1>;

const items = ["Apple", "Banana", "Cherry"];
const list = (
  <ul>
    {items.map(item => <li key={item}>{item}</li>)}
  </ul>
);

You can use any valid JavaScript expression here - function calls, ternary operators, even arithmetic. Just remember: no statements (like if/else or for loops) directly in JSX. You'll need to use them outside or use ternary operators instead.

Self-Closing Tags

In JSX, every tag must be closed - even self-closing ones! This is different from HTML where you can sometimes get away with unclosed tags. In JSX, you must write <img /> not <img>, and <br /> not <br>. Think of it as JSX being strict but fair.

const element = (
  <div>
    <h1>Title</h1>
    <p>Paragraph</p>
    <img src="photo.jpg" alt="A photo" />
    <br />
    <input type="text" />
  </div>
);

This strictness is actually a good thing. It catches errors early and makes your code more predictable. Plus, once you get used to it, it becomes second nature!

JSX vs HTML Differences

JSX looks like HTML, but there are some key differences. The most common gotcha is the className attribute. In HTML, you use class, but in JSX it's className. This is because class is a reserved word in JavaScript.

Another difference is style. In HTML, you write style="color: red;". In JSX, you pass an object: style={{color: 'red'}}. And don't forget camelCase for multi-word properties like backgroundColor instead of background-color.

const styled = (
  <div className="container" style={{color: 'blue', fontSize: '16px'}}>
    <p className="text">Hello JSX!</p>
  </div>
);
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What is JSX?