JSX lets you write HTML-like code inside JavaScript. It makes building user interfaces easier and clearer.
0
0
JSX syntax rules in React
Introduction
When creating React components that display UI elements.
When you want to mix JavaScript logic with HTML structure.
When you need to add dynamic content inside your UI.
When you want to keep your UI code readable and organized.
Syntax
React
const element = <tagName attributeName={value}>Content</tagName>;Use curly braces {} to insert JavaScript expressions inside JSX.
Every JSX tag must be closed, either with a closing tag or self-closing slash.
Examples
A simple JSX element with text inside an h1 tag.
React
const greeting = <h1>Hello, world!</h1>;Using curly braces to insert a JavaScript variable inside JSX.
React
const name = 'Alice'; const greeting = <h1>Hello, {name}!</h1>;
Self-closing tag for an image element with attributes.
React
const image = <img src="logo.png" alt="Logo" />;
JSX can contain nested elements like lists.
React
const list = <ul> <li>Item 1</li> <li>Item 2</li> </ul>;
Sample Program
This React component uses JSX to create a welcome message. It shows how to insert a variable, use semantic HTML tags, and add accessibility with aria-label and alt attributes.
React
import React from 'react'; function WelcomeMessage() { const userName = 'Sam'; return ( <section aria-label="welcome section"> <h2>Welcome, {userName}!</h2> <p>We are glad to see you here.</p> <img src="welcome.png" alt="Welcome illustration" /> </section> ); } export default WelcomeMessage;
OutputSuccess
Important Notes
JSX must have one parent element wrapping all content.
Use camelCase for attribute names like className instead of class.
Comments inside JSX use curly braces and JavaScript comment syntax: {/* comment */}.
Summary
JSX lets you write HTML-like code inside JavaScript for React UI.
Use curly braces {} to add JavaScript expressions inside JSX.
Always close tags and use one parent element per JSX block.