Introduction to JSX | Day 2
Tags: webdev, react, javascript, beginners
Published: 2022-01-01 16:57:14


### What

JSX Stands For **JavaScript Syntax Extension.**

It lets us to integrate the UI(HTML) into the JavaScript Code.

### Why

By using this we are able to write the HTML code into the JavaScript.

But, HTML isn’t valid JavaScript ,if we use the HTML in our code then will throw an error.

So for the JSX to work we use a **Transpiler** called **Babel.**

**Babel converts the JSX into the valid JavaScript Code.**


![JSX](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iqevsmsffgknm8objioy.png)
**But what the Transpilers does??**

- **So they are the Tools that read the source code written in one programming language and produce equivalent code in another language.**
- And **Babel** is also a **Transpiler.**
- **More Functions of a Transpilers.**
    
    Have u ever heard of the language like **Typescript or any other language that is used in place of JavaScript.**
    
    These language also uses the **Transpilers to convert their code into Valid javaScript Code.**
    
    The point of using these languages that they are more easy to learn in referance to the JavaScript. 
    

### How

So The JSX You Write is converted in the JavaScript

**Like, This** 

```jsx
<div>
     <h3>JSX Demo</h3>
      <img src="image.src"/>
</div>
```

**Compiles into** 👇

```jsx
React.createElement(
			"div", null,
			React.createElement("h3", null, "JSX Demo"),
			React.createElement("img", { src: "image.jpg})
);

//You can also write this javaScript code instead of the JSX the program will work the 
same way.
```

**You can also try it out on** 👇🏻

[Babel · The compiler for next generation JavaScript](https://babeljs.io/repl#?browsers=&build=&builtIns=false&corejs=3.6&spec=false&loose=false&code_lz=AQHgJglgbgfAUMRSQAsDMMBSBlAGsAEQFMBbAexAHp14lkISBzYAZwCcBjAXgCIGBDRkQB0AKwAOjHpXhVIsOEA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=react&prettier=false&targets=&version=7.16.7&externalPlugins=&assumptions=%7B%7D)

### Embedding JavaScript in JSX

- **To use the JavaScript in JSX u have to enclose them in the Curly braces `{}`.**

**Like,**

```jsx
class Demo extends React.Component{
		render(){
			return <h3>Your Marks are : {12*6}</h3>;	
		}
}
```

- **U can use loops ,conditionals or many things in Curly Braces `{}` .**

**The More Better Example of Conditional** 👇

```jsx
//Mood Representer 
function getName(){
    const names = ["Rajiv","Sanjay","Michel","Harry","Honey","Jayant"];
    return names[Math.floor(Math.random()*names.length)];
}


function getMood(){
    const Moods= ["😇","😀","😄","😁","😆","😅","😂","🤣","😊","😇","😍"];
    return  Moods[Math.floor(Math.random()*Moods.length)];
}

class Moods extends React.Component{
    render(){
        return (<h3>{getName()} mood is : {getMood()}</h3>)
    }
}

class App extends React.Component{
    render(){
        return(
            <div>
                <Moods/>
                <Moods/>
                <Moods/>
            </div>
        )
    }
}

ReactDOM.render(<App/>,document.getElementById('root'));
```

### Conditionals in JSX →

**JSX** doesn’t supports the loops and other conditional expressions, So we have to use the JavaScript to handles the Conditions.

You can refer to this Blog page to learn more about conditional expressions implementation. 

[Conditional rendering in React: 9 methods with examples - LogRocket Blog](https://blog.logrocket.com/conditional-rendering-in-react-c6b0e5af381e/)

Here are the what I have learned and used.

1. **Using `if else` ⇒**

```jsx
//Magic Number 

function getNum() {
  return Math.floor(Math.random() * 10 + 1);
}

// Using if and else
class MagicNum extends React.Component{
     render(){
       const num = getNum();
       let msg;
       if(num===7){
         msg = "Congrates!!!!"
       }
       else{
         msg = "Better luck next Time";
       }
       return (
         <div>
           <h1>Your Number is : {num}</h1>
           {msg}
         </div>
       );
     }
 }

//Using Ternary Operator
class MagicNum extends React.Component {
  render() {
    const num = getNum();
    return (
      <div>
        <h1>Your Number is : {num}</h1>
        <p>{num===7? "Congrats!!!" : "Better luck next time" }</p>
      </div>
    );
  }
}

//Using & opeartor
class MagicNum extends React.Component {
  render() {
    const num = getNum();
    return (
      <div>
        <h1>Your Number is : {num}</h1>
        <p>{num === 7 ? "Congrats!!!" : "Better luck next time"}</p>

        {num === 7 && (
          <img src="https://images.unsplash.com/photo-1641005361416-fba29d009bd2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwyM3x8fGVufDB8fHx8&auto=format&fit=crop&w=600&q=60" />
        )}
      </div>
    );
  }
}

ReactDOM.render(<MagicNum />, document.getElementById("root"));

```