JSX - Combining UI and Logic together

JSX - JavaScript Syntax Extension.

JSX is written using tags like format in JavaScript file and if you want to insert some JavaScript code inside the JSX tags you can just do that by putting JS code inside curly braces.

JSX helps in creating React Elements

Example :

       const name = "John";
       const element = <h1>Hello {name}</h1>

Why JSX?

JSX helps you in combining the rendering logic with UI logics like ;

  • How Events are handled.
  • How States change over time.
  • How data is prepared for display.

React doesn't separate the technologies by putting markup and logic in different files. It uses the concept of loosely coupled units called "Components" that have both Tags like structure plus the JS logic.

Embedding Expressions in JSX

You can put any valid JavaScript Expression inside curly braces.

    let groceryCost = 45;
    let stationaryCost = 50; 

    const totalCostElement = <h1> The total amount spent  is {groceryCost + stationaryCost}</h1>

JSX is an expression too After compilation JSX becomes regular JavaScript function calls and evaluates to JS code.

Specify Attributes with JSX

  • Using string literals
     const element = <a href="https://www/google.com">Google Link </a>l
  • Using curly braces to embed a JavaScript expression in an attribute. When you put JS expression in an attribute, you don't need to put quotations around curly braces.
     const image = <img src = {user.picURL}></img>

JSX prevents Injection Attacks

In JSX everything is converted to a string before getting rendered. This helps prevent XSS(cross site scripting) attacks.

JSX Represents Object

Babel(A JavaScript compiler) compiles JSX down to React.createElement() calls.

React.createElements() creates objects for the JSX code you write.

For example

     const element = (
             <h1 className="greetings">
                      Hello World
              </h1>
     )

Gets converted to an object.

image.png

React reads these objects and uses them to construct the DOM and keep it up to date.

Resources