Section 32 – Lessons 417 & 418 – Complete 2020 Web Development Bootcamp

Lesson 417 – Javascript Expression in JSX & ES6 Template Literals

JSX allows us to insert html inside a javascript file. It also allows us to insert javascript inside the html which is inside the javascript file.

The code below is an example of how to use javascript within html which is within a javascript file –

const name = "Shane";

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

In the above code, the javascript {name} sits inside the html h1 element. This will render the words “Hello Shane!” to the viewer.

The first challenge is to add a constant variable equal to a number and then use that variable in a paragraph which displays “Your lucky number is (the number created by the constant variable)”. This is the code that completes the challenge –

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

const name = "Shane";
const num = 7;

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

Using JSX you can insert any javascript expression between the {} braces. However, you can’t write javascript statements like an if/else statement.

The next challenge is to refactor the above code to include a first and last name in the h1 element. This is how I solved this challenge –

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

const fName = "Shane";
const lName = "Pinder";
const num = 7;

ReactDOM.render(
  <div>
    <h1>Hello {fName + " " + lName}!</h1>
    <p>Your lucky number is {num}.</p>
  </div>,
  document.getElementById("root")
);

There are two other ways it can be solved. The first is this –

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

const fName = "Shane";
const lName = "Pinder";
const num = 7;

ReactDOM.render(
  <div>
    <h1>Hello {fName} {lName}!</h1>
    <p>Your lucky number is {num}.</p>
  </div>,
  document.getElementById("root")
);

The third way it can be solves is using an ES6 template literal like this –

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

const fName = "Shane";
const lName = "Pinder";
const num = 7;

ReactDOM.render(
  <div>
    <h1>Hello {`${fName} ${lname}`}!</h1>
    <p>Your lucky number is {num}.</p>
  </div>,
  document.getElementById("root")
);

Lesson 418 – Javascript Expressions in JSX Practice

The is the challenge given in this lesson –

//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.

This is my solution –

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

const yourName = "Shane Pinder";

ReactDOM.render(
  <div>
    <p>Created by {yourName}.</p>
    <p>Copyright {new Date().getFullYear()}.</p>
  </div>,
  document.getElementById("root")
);