React js

Templating using JSX

Templating Using JSX in React

What is JSX?

  • JSX stands for JavaScript XML.

  • It’s a syntax extension for JavaScript used in React to write HTML-like code inside JavaScript.

  • Makes writing UI components easier and more readable by mixing markup with logic.


Why Use JSX?

  • Declarative and expressive way to describe UI.

  • Allows embedding JavaScript expressions inside markup.

  • React compiles JSX into regular JavaScript calls (React.createElement) under the hood.


Basic JSX Syntax

jsx
const element = <h1>Hello, world!</h1>;

This looks like HTML but is actually JSX — a syntax that compiles into JavaScript.


Embedding JavaScript Expressions

You can embed any JavaScript expression inside curly braces {} in JSX:

jsx
const name = 'Alice';
const greeting = <h1>Hello, {name}!</h1>;

You can also use functions, calculations, or any valid expression:

jsx
const user = { firstName: 'Alice', lastName: 'Smith' };
const element = <h1>Hello, {user.firstName + ' ' + user.lastName}!</h1>;

JSX with Attributes

You can pass attributes similar to HTML, but some attribute names differ because JSX is JavaScript:

jsx
const image = <img src="logo.png" alt="Logo" width={100} />;
  • Use camelCase for event handlers: onClick, onChange, etc.

  • For attributes that expect numbers, pass them without quotes: {100}, not "100".


JSX with Children and Nesting

JSX can contain nested elements:

jsx
const element = (
<div>
<h1>Welcome</h1>
<p>This is a JSX example.</p>
</div>
);

Conditional Rendering in JSX

Use JavaScript conditions inside JSX:

jsx
const isLoggedIn = true;

const greeting = (
<div>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>}
</div>
);


JSX Under the Hood

JSX code compiles to JavaScript like this:

js
const element = React.createElement(
'h1',
null,
'Hello, world!'
);

You don’t write React.createElement manually — JSX does it for you!


Summary

  • JSX lets you write HTML-like templates directly inside JavaScript.

  • Supports embedding expressions and logic inside templates.

  • Makes React components more readable and easier to write.

Leave a Reply

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