JSX: Writing Markup in React JS

JSX (JavaScript XML) is a syntax extension for JavaScript that looks similar to HTML. It's used in React to describe what the UI should look like. This blog will guide you through the basics of writing markup with JSX for absolute beginners.


What is JSX?

JSX allows you to write HTML-like syntax directly within your JavaScript code. This makes it easier to create and visualize UI components in React.

Example: Basic JSX Syntax

const element = <h1>Hello, World!</h1>;

Why Use JSX?

1. Readability: JSX makes your code more readable and easier to understand.

2. Component Structure: It helps structure your components clearly by mixing HTML-like elements with JavaScript.

Embedding Expressions in JSX

You can embed JavaScript expressions within curly braces {}.

Example:

const name = "Alice";
const greeting = **<h1>Hello, {name}!</h1>;**

Creating Components with JSX

Components are the building blocks of a React application. You can create them using functions or classes.

Example: Function Component

function Welcome(props) {
    return <h1>Welcome, {props.name}!</h1>;
}

JSX Attributes

Just like HTML, you can pass attributes to JSX elements. However, JSX uses camelCase for naming.

Example:

const image = <img **src="path/to/image.jpg" alt="Description"** />;

Using Class and Style Attributes

You should use className instead of class and style as an object for inline styles.

Example:

const divStyle = {
    color: 'blue',
    backgroundColor: 'lightgray',
};

const element = <div className="my-class" **style={divStyle}**>Styled Div</div>;

Conditional Rendering

You can use JavaScript operators to conditionally render elements.

Example:

const isLoggedIn = true;
const greeting = **isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>;**

Lists and Keys

Render lists of elements using the map() function, and ensure each element has a unique key prop.

Example:

const fruits = ['Apple', 'Banana', 'Cherry'];
const fruitList = fruits.map((fruit, index) => <li key={index}>{fruit}</li>);

JSX is a powerful feature of React that makes writing UI markup simple and intuitive.