JSX in depth in React.js

React JSJavascript LibraryFront End Technology

JSX simply creates a React element using createElement method in the end.

Example

<FormButton color="green" buttonSize={10}> Submit </FormButton>

Will be converted to −

React.createElement(
   FormButton,
   {color: 'green', buttonSize: 10},
   'Submit’
)

Self-closing tags are also possible to add.

Capitalizing the custom React Element

The custom react element must be named with first character in capital so that React will be able distinguish between the html element and the react element.

As Jsx gets converted to React.createElement, the React library must be in scope. For that we have to import the React if jsx needs to use.

Accessing the inner properties using dot operator

The inner properties of an element can be accessed using the dot operator.

Example

<FormComponent.TextArea size=”50”/>

Runtime choosing the type of an Jsx element

The general expression can not be used in the type of React element. First we have to assign it to a capitalized variable then we can use that variable.

Example

import React from 'react';
import { Cricket, Football } from './sportsTypes';
const components = {
   cricket: Cricket,
   football: Football
};
function Story(props) {
   // Below expression is wrong and cannot be used this way.
   return <components[props.cricket] player={props.name} />;
}

To make it work, we will assign it to a capitalized letter −

import React from 'react';
import { Cricket, Football } from './sportsTypes';
const components = {
   cricket: Cricket,
   football: Football
};
function Story(props) {
   // Correct! JSX type can be a capitalized variable.
   const Sport = components[props.cricket];
   return <Sport player={props.name} />;
}

Props usage in jsx

Props can be a jsx expression

Example

<Player score={4+6+4} />

The score prop will be calculated as 14

The conditional statement like if , for can not be used directly in jsx code but they can be used separately and their result variables can be used in jsx.

Props can be string literals −

<Player name={‘Steve’}/>

Or

<Player name=”Steve”/>

The props value will default to true if not provided. This is just to be compatible with the default behavior of html.

Example

<Player isPlaying />

Is equal to

<Player isPlaying={true} />

The spread operator can be used to pass the props −

<Player {…props} />

Children element in jsx

The content between the start tag and end tag is the jsx children element.

<Player> Steve </Player>

The children can be jsx expression or function as well. If jsx children are among the type Boolean null , undefined then they will be ignored.

raja
Published on 05-Sep-2019 08:00:25
Advertisements