Understanding JSX in React

🧠 What is JSX?

JSX is a syntax extension for JavaScript that looks like HTML. It’s used in React to describe what the UI should look like.

Even though it looks like HTML, it gets compiled to JavaScript under the hood.


✅ Example 1: Basic JSX

In your App.jsx, write:

function App() {
  return (
    <div>
      <h1>Hello from JSX!</h1>
      <p>This is a paragraph inside a React component.</p>
    </div>
  );
}

export default App;

✅ This is valid JSX. Looks like HTML, but it’s in a .jsx file.

⚠️ JSX Rules to Remember

1. Only One Parent Element

You must return a single parent element.

✅ Correct:

return (
  <div>
    <h1>Hello</h1>
    <p>World</p>
  </div>
);

❌ Incorrect:

// This will cause an error
return (
  <h1>Hello</h1>
  <p>World</p>
);

Use a single wrapper like <div> or <> (a fragment) if you don’t want an extra tag.

2. Use className instead of class

Since class is a reserved word in JavaScript, React uses className for CSS classes.

return <h1 className="title">Hello</h1>;

3. Use {} to Embed JavaScript

You can use curly braces {} to insert JavaScript inside JSX.

const name = "Alice";

return <h1>Hello, {name}!</h1>;

4. JSX Must Be Properly Closed

Always self-close tags like <img />, <input />, etc.

✅ Correct:

<img src="logo.png" alt="Logo" />

❌ Incorrect:

<img src="logo.png">

✅ Example 2: Using JavaScript inside JSX

function App() {
  const user = {
    name: "John",
    age: 30,
  };

  return (
    <div>
      <h2>Hello, {user.name}</h2>
      <p>Age: {user.age}</p>
      <p>Status: {user.age >= 18 ? "Adult" : "Minor"}</p>
    </div>
  );
}

export default App;

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *