jsx

A Deep Dive in JSX

shamantasristy

Shamanta Sristy

Posted on May 7, 2021

A Deep Dive in JSX

To know JSX in-depth, we should have a clear idea of what is JSX and is used? The full form of JSX is Javascript XML. To clear the whole JSX concept first, we will discuss what is JSX?

What is JSX?

JSX is an XML/HTML-like syntax used by React.js which extend Javascript so that XML/HTML-like text can co-exist with JavaScript/React code.

Why JSX?

JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() and/or appendChild() methods.JSX converts HTML tags into react elements.
For example, with JSX , we can write code like below:

const firstElement = <h1>My first JSX</h1>;

ReactDOM.render(firstElement, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

And without JSX:

const firstElement= React.createElement('h1', {}, 'I do not use JSX!');

ReactDOM.render(firstElement, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

From above, we can see that, with JSX writing code for React application is quite easy.

Expressions in JSX

Inserting a Single Line HTML

In JSX we can write expressions inside curly braces { } .
The expression can be a React variable, or property, or any other valid JavaScript expression. JSX will execute the expression and return the result:

const text = <h1> This is an expression in JSX </h1>
Enter fullscreen mode Exit fullscreen mode

Inserting A Block of HTML

To insert a block of HTML expression on multiple lines, we need to put the HTML block inside parentheses:

const list= (
  <ul>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Cherries</li>
  </ul>
);
Enter fullscreen mode Exit fullscreen mode

Specifying The React Element Type

The first part of a JSX tag determines the type of the React element.

Capitalized types indicate that the JSX tag is referring to a React component.

React Must Be in Scope

Since JSX compiles into calls to React.createElement, the React library must also always be in scope from JSX code.

For example, both of the imports are necessary in this code, even though React and CustomButton are not directly referenced from JavaScript:

import React from 'react';
import CustomButton from './CustomButton';

function WarningButton() {
  // return 
React.createElement(CustomButton, {color: 'red'}, null);  return <CustomButton color="red" />;
}
Enter fullscreen mode Exit fullscreen mode

User-Defined Components Must Be Capitalized

React recommend naming components with a capital letter. If a component is declared that starts with a lowercase letter, we need to assign it to a capitalized variable before using it in JSX.

For example, this code will not run as expected:

import React from 'react';

// This is a component and should be capitalized:function Hello(props) { This use of <div> is legitimate because div is a valid HTML tag:
  return <div>Hello {props.toWhat}</div>;
}

function HelloWorld() {
  // React knows <Hello /> is a component because it's capitalized. 
   return <Hello toWhat="World" />;}
Enter fullscreen mode Exit fullscreen mode

Choosing the Type at Runtime

We cannot use a general expression as the React element type. If we do want to use a general expression to indicate the type of the element, we have to just assign it to a capitalized variable first.
For example:

import React from 'react';
import { PhotoStory, VideoStory } from './stories';

const components = {
  photo: PhotoStory,
  video: VideoStory
};

function Story(props) {
  // JSX type can be a capitalized variable. 
  const SpecificStory = components[props.storyType];
  return <SpecificStory story={props.story} />;}
Enter fullscreen mode Exit fullscreen mode

Props in JSX

There are several different ways to specify props in JSX

JavaScript Expressions as Props

Any JavaScript expression can be passed as a prop, by surrounding it with {}. For example, in this JSX:

<MyComponent foo={1 + 2 + 3 + 4} />
Enter fullscreen mode Exit fullscreen mode

String Literals

String literals can be passed as a prop. These two JSX expressions are equivalent:

<MyComponent message="hello world" />
<MyComponent message={'hello world'} />
Enter fullscreen mode Exit fullscreen mode

Spread Attributes

If we already have props as an object, and we want to pass it in JSX, we can use ... as a “spread” operator to pass the whole props object. These two components are equivalent:

function App1() {
  return <Greeting firstName="Ben" lastName="Hector" />;
}

function App2() {
  const props = {firstName: 'Ben', lastName: 'Hector'};
  return <Greeting {...props} />;}
Enter fullscreen mode Exit fullscreen mode

Children in JSX

There are several different ways to pass children:

String Literals

We can put a string between the opening and closing tags and props. children will just be that string. This is useful for many of the built-in HTML elements. For example:

<MyComponent>Hello world!</MyComponent>
Enter fullscreen mode Exit fullscreen mode

JSX Children

We can provide more JSX elements as the children. This is useful for displaying nested components:

<MyContainer>
  <MyFirstComponent />
  <MySecondComponent />
</MyContainer>
Enter fullscreen mode Exit fullscreen mode

JavaScript Expressions as Children

Passing any JavaScript expression as children in JSX is allowed, by enclosing it within {}. For example, these expressions are equivalent:

<MyComponent>foo</MyComponent>

<MyComponent>{'foo'}</MyComponent>
Enter fullscreen mode Exit fullscreen mode

Functions as Children

Normally, JavaScript expressions inserted in JSX will evaluate to a string, a React element, or a list of those things.

function Repeat(props) {
  let items = [];
  for (let i = 0; i < props.numTimes; i++) {    items.push(props.children(i));
  }
  return <div>{items}</div>;
}

function ListOfTenThings() {
  return (
    <Repeat numTimes={10}>
      {(index) => <div key={index}>This is item {index} in the list</div>}    </Repeat>
  );
}
Enter fullscreen mode Exit fullscreen mode

Children passed to a custom component can be anything, as long as that component transforms them into something React can understand before rendering. This usage is not common, but it works if you want to stretch what JSX is capable of.

Booleans, Null, and Undefined Are Ignored

false, null, undefined, and true are valid children. They simply don’t render. These JSX expressions will all render to the same thing:

<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>
Enter fullscreen mode Exit fullscreen mode

If You are new to the JSX concept more's here.

💖 💪 🙅 🚩
shamantasristy
Shamanta Sristy

Posted on May 7, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related