How Can We Help?
< All Topics

React JSX

What is React JSX

JSX stands for JavaScript XML. It is not a different language, it’s a syntax extension used in React to define and describe the structure of React elements and makes it easier to write and add HTML in React.

It allows you to write HTML elements directly in your JavaScript code.

Here is an example of without JSX:

Earlier we had to make an HTML element or append it into existing ones with these traditional DOM manipulation methods createElement() / appendChild()

import React from 'react';

function App() { return (
React.createElement('h1', {}, 'Hello World!')
);
}

export default App;

Here is an example of JSX:

Look, Using JSX we can write HTML syntax directly like this.

import React from 'react';

function App() { return (
<h1>Hello World!</h1>
);
}

export default App;

JSX Embedding Expressions

You can write JavaScript expressions inside the curly braces {} in JSX. Here is some code examples of JSX expressions given below for better understanding:

Variables:

function App() {
const name = "Code With Random" return (
<h1>Hello, {name}</h1>
);
}
export default App;

// output
// Hello, Code With Random

Mathematical Operations:

function App() { return (
<h1>{10 + 5}</h1>
);
}

export default App;

// output
// 15

Ternary Operators:

function App() { const age = 22; return (
<h1>{age >= 18 ? "You are a Adult" : "You are not a adult!"}</h1>
);
}

export default App;

// output
// "You are a Adult"

JSX Attributes

In JSX, you can use attributes in HTML elements as regular HTML. Remember, JSX attributes use camelCase naming convention so when you add attributes, you have to specify its name using camelCase naming convention. For example, class attribute becomes className.

Here are some examples of JSX attributes given below:

Class and style Attributes

function App() { return (
<h1 className="title" style={{color: "green"}}> Code With Random
</h1>
);
}

export default App;

Some more examples of camelCase naming convention:

htmlFor instead of for

<label htmlFor="input1"></label>

onClick instead of onclick

<button onClick={myFunction}>Login</button>

tabIndex instead of tabindex, etc.

Dynamic Attributes

You can set attributes dynamically based on variables or expressions. For example:

function App() {
const isDisabled = true;
const buttonText = "Login" return (
<button disabled={isDisabled}>{buttonText}</button>
);
}

export default App;
Table of Contents