📝 JSX Syntax and Expressions
JSX lets you write HTML-like syntax inside JavaScript. It is syntactic sugar for React.createElement() and allows you to embed dynamic content using JavaScript expressions.
🔧 Basic JSX Syntax
const element = <h1>Hello, world!</h1>;
ReactDOM.render(element, document.getElementById('root'));
This renders the text inside an <h1> to the DOM.
🔁 Embedding Expressions in JSX
Use curly braces { } to embed JavaScript expressions in JSX. You can use variables, functions, and any valid JavaScript expression.
const name = 'React';
const element = <h1>Welcome to {name}!</h1>;
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
const user = { firstName: 'John', lastName: 'Doe' };
const element = <h2>Hello, {formatName(user)}</h2>;
📌 Conditional Expressions
JSX supports conditional rendering using the ternary operator or logical &&.
const isLoggedIn = true;
const element = <div>{isLoggedIn ? 'Logout' : 'Login'}</div>;
const messages = [];
const element = <div>{messages.length > 0 && 'You have new messages'}</div>;
🔁 Looping with Expressions
Use map() to dynamically render lists in JSX:
const items = ['Apple', 'Banana', 'Orange'];
const element = (
<ul>
{items.map(item => <li key={item}>{item}</li>)}
</ul>
);
⚠️ Syntax Rules
- Wrap adjacent JSX tags in a parent element (or use fragments
<> </>). - Use
classNameinstead ofclass. - JSX attributes are camelCase (e.g.,
onClick,tabIndex). - All tags must be closed (e.g.,
<img />).
⚙️ JSX is Just Syntax
Under the hood, JSX is converted by Babel into calls to React.createElement(), which builds virtual DOM objects that React can efficiently update.


