Curriculum
Course: React
Login

Curriculum

React

Text lesson

Attribute class = className

The class attribute is commonly used in HTML, but since JSX is rendered as JavaScript and class is a reserved keyword in JavaScript, you must use className instead in JSX.

Use the className attribute instead.

JSX addresses this by using className instead. When JSX is rendered, it converts className attributes into class attributes.

Example

In JSX, use the className attribute instead of class.

const myElement = <h1 className="myclass">Hello World</h1>;

Conditions – if statements

React supports if statements, but they cannot be used directly inside JSX. To implement conditionals in JSX, place the if statements outside of the JSX or use a ternary expression.

Option 1:

Place if statements outside of the JSX code.

Example

Display “Hello” if x is less than 10; otherwise, display “Goodbye.”

const x = 5;
let text = "Goodbye";
if (x < 10) {
  text = "Hello";
}
const myElement = <h1>{text}</h1>;

Option 2:

Use a ternary expression instead.

Example

Use a ternary expression to display “Hello” if x is less than 10, otherwise display “Goodbye.”

const x = 5;
const myElement = <h1>{(x) < 10 ? "Hello" : "Goodbye"}</h1>;
To embed a JavaScript expression inside JSX, wrap the JavaScript code with curly braces {}.