React Lesson #2 - More on JSX, ES6 Template Literals

React Lesson #2 - More on JSX, ES6 Template Literals

By using JSX, we can insert HTML inside JavaScript and JavaScript inside that HTML.

Before moving forward make sure you have these codes/files in the following structure:

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>JSX Challenge</title>
    <link rel="stylesheet" href="./styles.css" />
  </head>
  <body>
    <div id="root"></div>
    <script src="../src/index.js"></script>
  </body>
</html>

Now, let's use javascript inside HTML which is inside javascript to demonstrate JSX. We will do this in index.js file.

import React from "react";
import ReactDOM from "react-dom";

const name = "Ratan";

ReactDOM.render(<h1>Hello {name}!</h1>, document.getElementById("root"));

We have used a string variable which contains the name and to put it in the HTML, we put curly braces on both ends of the variable. This successfully demonstrates the working of JSX.

Now, we can also put any expressions inside the curly braces like 1+2, etc. For example, generating a random number.

import React from "react";
import ReactDOM from "react-dom";

const name = "Ratan";
// const lucky_num = 7;

ReactDOM.render(
  <div>
    <h1>Hello {name}!</h1>
    <p>Your lucky number is {Math.floor(Math.random() * 10)}.</p>
  </div>,
  document.getElementById("root")
);

Note: We can only put expressions in the curly braces and not statements like if else statements, loops, etc.

ES6 Template Literals

import React from "react";
import ReactDOM from "react-dom";

const fname = "Ratan";
const lname = "Sharma";
// const lucky_num = 7;

ReactDOM.render(
  <div>
    <h1>Hello {`${fname} ${lname}`}!</h1>
    <p>Your lucky number is {Math.floor(Math.random() * 10)}.</p>
  </div>,
  document.getElementById("root")
);

In the above code, in h1 tag ES6 string literals are demonstrated. We create them using a dollar ($) sign followed by curly braces ({}) with no space in between the $ and {}. Make sure the string is enclosed on both ends using (``) single back-ticks.

Here is what is actually happening there:

  1. The variables fname and lname are converted into a string

  2. The string is then converted into HTML element

Practice example

//Create a react app from scratch.
//It should display 2 paragraph HTML elements.
//The paragraphs should say:
//Created by YOURNAME.
//Copyright CURRENTYEAR.
//E.g.
//Created by Angela Yu.
//Copyright 2019.
import React from "react";
import ReactDOM from "react-dom";

const YOURNAME = "Ratan";

const date = new Date();
const CURRENTYEAR = date.getFullYear();

ReactDOM.render(
  <div>
    <p>Created by {YOURNAME}.</p>
    <p>Copyright {CURRENTYEAR}.</p>
  </div>,
  document.getElementById("root")
);