What is JSX in React ?

 

jsx elements

Introducing JSX


  const greet = <h1>Hello</h1>;

This funny tag syntax is neither a string nor HTML.

It is called JSX, and it is a syntax extension to JavaScript. We recommend using it with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript.

JSX produces React “elements”. We will explore rendering them to the DOM in the
 next section. Below, you can find the basics of JSX necessary to get you started.

Why JSX?

React embraces the fact that rendering logic is inherently coupled with other UI logic: how events are handled, how the state changes over time, and how the data is prepared for display.

Instead of artificially separating technologies by putting markup and logic in separate files, React separates concerns with loosely coupled units called “components” that contain both. We will come back to components in a further section, but if you’re not yet comfortable putting markup in JS, this talk might convince you otherwise.

React doesn’t require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code. It also allows React to show more useful error and warning messages.

With that out of the way, let’s get started!

Compiled By Babel

What is React with JSX, and how are JSX and Babel related ?

JSX can best be thought of as a markup syntax that very closely resembles HTML. React is a library which uses JavaScript functions to generate strings of HTML it inserts into a web page document’s body.

JSX makes writing React components, the building blocks of React UI, easier by making the syntax developers use for generating these strings of HTML almost identical to the HTML they will inject into the web page.

Babel parses JSX syntax, which browsers cannot understand, and transpiles your source code into JavaScript that is less human friendly but will run in browsers.



1-Embedding Expressions in JSX

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.


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

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

  var fName = "react js";
  var sName = "JSX"

  ReactDOM.render(
    <div>

      <h2>My Name is {fName}</h2> ,
      <h3>My SecondName is {sName}</h3>

    </div>,
    document.getElementById('root') //DOM --  JS ES6
  ); 

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


  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.


  // 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>
  );

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.


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


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


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


  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.



  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.

JSX Conditionals:

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

if else :

  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>;
 
Ternary Operator :


  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>;

&& Operator :


  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.


  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.


  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 keykey is a JSX attribute and the value should be something unique, similar to an id attribute.


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