Attributes in JSX
Although the 'class' attribute is commonly used in HTML, you cannot use it in JSX since it is rendered as JavaScript and the 'class' keyword is a reserved word in JavaScript. Instead, use the className attribute.
class Vs. className
The 'class' property in HTML is used to tell the browser the CSS class to use. Class, on the other hand, is a JavaScript reserved word.
Since JSX is compiled into JavaScript, conflicts can arise. To correct this, we use the 'className' attribute instead of class. It will compile into the HTML class property during the build process. The distinction between className and class is purely to assist JSX in determining what type of class we're working with.
Let us take an example:
const greetPeople = "Welcome to Coding Ninjas";
<h1 className="header">{greetPeople}</h1>

You can also try this code with Online Javascript Compiler
Run Code
When we compile this, we'll get the following:
<h1 class="header">Welcome to Coding Ninjas</h1>

You can also try this code with Online Javascript Compiler
Run Code
Comments in JSX
Let us take a look at an example of code.
<h1>This is an example for commenting out the code in React JSX. </h1>

You can also try this code with Online Javascript Compiler
Run Code
Now, let us comment out the above code.
{/*<h1>This is an example for commenting out the code in React JSX. </h1>*/}

You can also try this code with Online Javascript Compiler
Run Code
Tip: To add or remove a comment, use the Cmd + / (in Mac) or Ctrl + / (in Windows) shortcut keys instead of typing it manually.
Self Closing tags in JSX
When it comes to rendering HTML, browsers are generally chill. JSX, on the other hand, needs that all tags to be closed. This means that certain components, including <input> and <img>, must be closed with'/'. JSX will throw an error if a tag is not self-closed.
Here's an invalid illustration:
/* This code shows error */
<div>
<br >
<p>Hello! How was your day?</p>
<p>Make sure to close all the self-closing tags!</p>
<hr >
</div>

You can also try this code with Online Javascript Compiler
Run Code
JSX Error:

Here's a valid illustration:
<div>
<br/>
<p>Hello! How was your day?</p>
<br/>
<img src={imgLink} />
</div>

You can also try this code with Online Javascript Compiler
Run Code
Adding Javascript Code in React JSX
We've just used HTML tags as part of JSX, though it becomes more useful when we add JavaScript code to JSX.
To include JavaScript code in JSX, wrap it in curly brackets as follows:
const Application = () => {
const numberTaken = 35;
return (
<div>
<p>Number: {numberTaken}</p>
</div>
);
};

You can also try this code with Online Javascript Compiler
Run Code
We can only write a JSX expression that evaluates to some value inside the curly brackets. As a result, the use of curly brackets is sometimes referred to as JSX Expression Syntax.
In a JSX expression, you can include the following elements:
- String examples like "Coding ninjas".
- A number such as 40.
- [1, 2, 3, 4, 5, 6] is an example of an array.
- The property of an object that will be evaluated to a value.
- A function call that returns a value that could be JSX.
- A map method that returns a new array every time.
The items listed below are invalid and cannot be used in a JSX expression:
- A while loop or for loop, or any other loop
- A declaration of a variable
- A declaration of a function
- An object
- An if condition statement
When it comes to an object, it's unclear how it should be displayed. Should it be displayed as JSON or as comma-separated key-value pairs? If we try to display the object in a JSX expression, we'll get an error. Instead, we can use object properties.
When we use 'undefined', 'null', or 'boolean' inside JSX, the UI will not display them.
The curly braces can also be used to set 'attributes' and 'event listeners' in JSX with JavaScript. Let us look at an example:
const altImageDescription = "Let us look at a picture of a dog.";
function randomEvent(e){}
const dogImage = (
<img
src="images/dog.jpg"
alt={altImageDescription}
onClick={randomEvent}
/>
);

You can also try this code with Online Javascript Compiler
Run Code
Event Listeners in JSX
Like HTML elements, JSX elements can have event listeners. Working with event listeners is a constant in React programming.
The name of the event listener attribute should be something like onClick or onMouseOver: the word 'on' followed by the sort of event you're monitoring. The value of an event listener attribute should be a function.
Note that event listener names in HTML, such as onclick or onmouseover, are expressed in all lowercase. Event listener names in JSX, such as onClick and onMouseOver, are written in camelCase.
Conditionals in React JSX
We're under the assumption that all you have to do is wrap your JavaScript in curly brackets and it'll function automatically. This, however, will not work with conditionals. This is because JSX prefers that you return full blocks rather than using conditional logic to return sections of them.
The goal is to make things as simple as possible because breaking apart HTML blocks can quickly become a mess.
So, in JSX, how do you build conditionals? You must begin with the condition and then return whatever HTML block you desire.
Let us look at an example of the syntax:
if(random() === 'dog'){
text = <p className='dog'>random returned dog</p>;
}
else
{
text = <p className='somethingElse'>random returned something
else</p>;
}

You can also try this code with Online Javascript Compiler
Run Code
That's the JSX syntax for if statements. Then there's the case of ternary operators.
Let us look at an example of a ternary operator:
x ? y : z
But, exactly, what is the previous example implying? In short, x denotes the condition, y denotes what happens if x is true, and z denotes what happens if x is false.
Here's an example:
random() === 'dog' ? 'print dog' : 'print cat'

You can also try this code with Online Javascript Compiler
Run Code
Here's how you'd read the ternary example above: If random equals 'dog', ' print dog'; else,'print cat'. Within JSX HTML tags, you can use ternary operators.
Consider the following scenario:
const printDog (
<p>
{random() === 'dog' ? 'print dog' : 'print cat'}
</p>
);

You can also try this code with Online Javascript Compiler
Run Code
So we're left with the && operator.
The && operator is identical to the ? ternary operator, however, it does not include the second fallback condition. Basically, if the situation is true, take some action. Don't do anything if the condition doesn't apply.
The above example has been rebuilt with the && operator like this:
const printDog (
<p>
{random() === 'dog' && 'print dog' }
</p>
);

You can also try this code with Online Javascript Compiler
Run Code
Frequently Asked Questions
- Why must the React library be in scope from the JSX code?
Ans: The React library must always be in scope from your JSX code since JSX compiles into calls to React.createElement.
Despite the fact that React and CustomButton are not explicitly accessed from JavaScript, both imports are required in the following code:
import React from 'react';
import CustomButton from './CustomisedButton';
function warningButtonHere() {
// Return React.createElement(CustomisedButton, {color: 'green'}, null);
return <CustomisedButton color="green" />;
}

You can also try this code with Online Javascript Compiler
Run Code
The React library is already in scope as the React global, if we don't utilize a JavaScript bundler and load it from a <script> tag.
2. What are some of the advantages of using JSX?
Ans: The following are some of the advantages of using JSX:-
- In React, JSX makes it easy to write or add HTML.
- HTML tags may be easily converted to react elements using JSX.
- It is more efficient than regular JavaScript.
- We can use JSX to add HTML elements to the DOM without having to use the appendChild() or createElement() methods.
- We can utilize JSX inside if statements and for loops, assign it to variables, take it as arguments, and return it from functions because it is an expression.
- JSX protects against injection attacks, also known as XSS (cross-site scripting).
- It is type-safe, and most problems are discovered during compilation.
3. Why is it possible to use a ternary operator in JSX but not if statements?
Ans: If statements can be written in a variety of ways, which can become messy over time. The expected outcome with ternary ? operator and && operator is finite and absolute. If statements can include parent expressions, while ternaries can evaluate to a value.
4. Can we use JSX with any other language like python, PHP?
Ans: No, additional programming languages beyond JavaScript cannot be injected into JSX. Wrapping the JS expression in curly brackets is the only way to inject variable JavaScript expressions into JSX.
Key Takeaways
In this blog, we went over the fundamentals of React JSX, came to know the need for JSX and the attributes, and commenting on React code in JSX.
Here are some key points to remember:
- Every JSX tag is changed into a React component called React.createElement.
- Only items that evaluate to some value, such as string, number, array map method, and so on, are allowed in JSX Expressions, which are written inside curly brackets.
- When adding classes to an HTML element in React, we must use className instead of class.
- In React, all attribute names are written in camelCase.
- When used inside JSX, undefined, null, and boolean are not displayed on the UI.
You can also consider our React Js Course to give your career an edge over others.

Credits: GIPHY
Happy Developing!