React JSX
Tags: react, javascript
Published: 2019-09-25 12:42:55

---
title: React JSX
published: true
description: 
tags: #react #javascript
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/2rl5f0mcdqfhyjevk9tw.jpg
---
👋Hi, In this blog📖, I write about JSX which is the foremost thing to learn React.

Lets Start...🏃‍♂️🏃‍♂️🏃‍♂️

```javascript
const greet = <h1>Hello</h1>;
```
This code looks a bit confusing. It seems like javascript because it starts with `const` and ends with `;`. Again it seems like HTML because it also contains `<h1>Hello</h1>`.

We write this code in a JavaScript file. Despite what it looks like actually this code does not contain any HTML. The part looks like HTML `<h1>Hello</h1>`, is called JSX.

➡ JSX is a syntax extension for javascript. It is written for React. JSX is not a valid javascript. Web browser can't read it. If a javascript file contains JSX, that file needs to be compiled before ran. JSX compiler translates any JSX into a regular javascript.

## ✔JSX Element:

A basic unit of JSX is called the JSX element. An element describes what you want to see on the screen. Example of the JSX element given below.

```javascript
<h1>Hello</h1>
```

JSX elements are treated as a javascript expression. That means it can be saved in a variable, passed to a function, stored in an object or an array.

```javascript
// Saved in a variable
const title = <h1>JSX</h1>;

// Stored in an Object
const obj = {
  title: <h1>React</h1>,
  subTitle: <h2>JSX</h2>
};
```

JSX elements can have attributes like HTML elements can. A single JSX element can have many attributes.

```javascript
const title = <h1 id="title">Introduction to JSX</h1>;
```

## ✔Nesting:

We can nest JSX elements inside of other JSX elements. If JSX expression takes up more than one line then we must wrap the expression in parentheses. We can also save nested JSX expression in a variable just like non-nested JSX expression.
```javascript
// Nested JSX
<a href="https://www.google.com"><h1>Click me</h1></a>

// For readability, we can use line break and indentation
(
  <a href="https://www.google.com">
    <h1>
      Click me
    </h1>
  </a>
)

// Nested JSX expression saved in a variable
const example = (
  <a href="https://www.google.com">
    <h1>
      Click me
    </h1>
  </a>
);
```
***✨✨✨Important rule, JSX expression must have only one outermost element. The first opening tag and the final closing tag of a JSX expression must belong to the same JSX element.***

```javascript
const example = (
  <div title="outer-most-element">
    <a href="https://www.google.com">
      <h1>
        Click me
      </h1>
    </a>
  </div>
);
```
## ✔className & htmlFor:

The grammar of JSX is mostly same as in HTML. In HTML we use `class` attribute but in JSX we can't use `class`, we have to use `className` instead. This is because JSX gets translated into JavaScript, and in JavaScript `class` is a reserved word. For same reason we can't use `for` in `<label></label>` element instead we have to use `htmlFor`.

```javascript
<h1 className="greet">Hello</h1>

<label htmlFor="firstName">First Name</label>
```
## ✔Self-Closing Tags:
When we write a self-closing tag in HTML, it is optional to include a forward slash before the final angle-bracket. But in JSX we have to include forward-slash otherwise it will raise an error.

```javascript
// In HTML
<img src="dog.jpg" >
<input type="text" >
<br>

// In JSX
<img src="dog.jpg" />
<input type="text" />
<br />
```

## ✔JavaScript Expressions in JSX:

We can use any JavaScript expressions in JSX elements by enclosing them within `{}` curly braces.

```javascript
// Variable
const greet = 'Hello World';

// Object
const person = {
  name: 'John Doe',
  age: 24,
  profession: 'Web Developer'
};

// Function
const greetings = () => 'Hello World';

// JavaScript Expressions in JSX
<h1>{10 + 5}</h1>

<h1>{greet}</h1>

<h1>{person.name}</h1>
<p>{person.age}</p>
<p>{person.profession}</p>

<h1>{greetings()}</h1>

```
we can also use JavaScript expressions in JSX elements attribute.
```javascript
const google = 'https://www.google.com';

<a href={google}>Click Me</a>
```

## ✔Event Listeners in JSX:

JSX elements can have event listeners just like HTML elements can. We can create an event listener by giving JSX elements a special attribute.

```javascript
onButtonClick = () => alert('Hello World!');

<button onClick={onButtonClick}>Click Me</button>
```

An event listener attributes value should be a function. In HTML, all event listener names are written in lowercase letters but in JSX event listener names are written in camelCase letters. You can see a list of supported event names [here](https://reactjs.org/docs/events.html#supported-events).

## ✔JSX Conditionals:

We can write JSX based on conditions. Some conditional examples are given below.

- 1️⃣ if else :
```javascript
let age = 18;
let message;

if (age >= 18) {
  message = (
    <h1>
      You can buy a drink.
    </h1>
  );
} else {
  message = (
    <h1>
      You can not buy a drink.
    </h1>
  );
}



// output will be
message = <h1>You can buy a drink</h1>;
```
***✨✨✨You can not inject an `if` statement into JSX.***

- 2️⃣ Ternary Operator :
```javascript
let age = 18;

const message = (
  <h1>
    {age >= 18 ? 'You can buy a drink.' : 'You can not buy a drink'}
  </h1>
);



// output will be
message = <h1>You can buy a drink</h1>;
```

- 3️⃣ `&&` Operator :

```javascript
let age = 18;

const message = (
  { age >= 18 && <h1>You can buy a drink.</h1> }
  { age < 18 && <h1>You can not buy a drink</h1> }
);



// output will be
message = <h1>You can buy a drink.</h1>;
```
## ✔The `.map()` array method:
To create a list of JSX elements, `.map()` is often used in React.

```javascript
const persons = ['Lily', 'Riyan', 'John'];

const listItems = persons.map(person => <li>{person}</li>);

<ul>{listItems}</ul>
```
The `{listItems}` will evaluate to an array. And we can use an array into a JSX elements i.e.

```javascript
const listItems = [
  <li>Lily</li>,
  <li>Riyan</li>,
  <li>John</li>
];

<ul>{listItems}</ul>



// output will be
<ul>
  <li>Lily</li>
  <li>Riyan</li>
  <li>John</li>
</ul>
```

## ✔Keys: 
When we make a list in JSX, we need to include `key`. `key` is a JSX attribute and the value should be something unique, similar to an `id` attribute.

```javascript
<ul>
  <li key="li-1">Example 1</li>
  <li key="li-2">Example 2</li>
  <li key="li-3">Example 3</li>
</ul>
```
Keys help React to identify which items have changed, added, or removed.

That's it, Thanks🙂 for reading and stay tuned🙋‍♂️.