Using JSX in React.js

React JSJavascript LibraryFront End Technology

JSX is like a template language with Power of JavaScript. It helps in creating the react elements. It’s an extension of JavaScript to include UI elements.

Example

let message = <h1>Hello World </h1>;

h1 tag is known html tag but with jsx we have created a variable containing the h1 tag with a hello world message.

Usefulness of jsx

Though it’s not mandatory to use jsx to create react elements. But its visibly appealing and helps in understanding the code in easy way. React embraces the concept of keeping UI logic and rendering logic together.

We can build different loosely coupled components for separation of concerns

Expression embedding :
let name = ‘Steve’;
const welcomeMessage = <h1>Welcome, {name} </h1>;
ReactDOM.render(
   welcomeMessage,
   document.getElementById(‘app’)
);

In above example, name is a variable with value as ‘Steve’ which is embedded with curly braces in const welcomeMessage.

Any valid JavaScript expression including functions will work in curly braces in jsx. Examples: { 5 *5 } will result into 25

Example of using function in jsx expression −

function getFullName(customer) {
   return customer.firstName + ' ' + customer.lastName;
}
const customer = {
   firstName: 'Amit',
   lastName: 'Sharma'
};
const welcomeCustomer = (
   <h1>
      Welcome, { getFullName(customer) } !
   </h1>
);
ReactDOM.render(
   welcomeCustomer,
   document.getElementById('app')
);

We can add multiple line jsx code by wrapping it inside brackets (). It also avoid the issues of automatic semicolon insertion. On compilation, the jsx code gets converted into the regular JavaScript.

JSX element can be passed as an argument or return from a function call. It can be used in a conditional statements as well.

Attributes on jsx element

The name of attribute used on jsx element follows camel case notations. Example : the class name attribute for adding css classes are named className (As class is a reserved keyword in JavaScript it uses className)

tabIndex − In regular html element it will be tabindex with all chars in lowercase but in jsx it will be tabIndex

We can give value to attribute using string literal like className=”App” or by using jsx expression with curly braces className={Test}

jsx element can contain the child elements and can be closed with /> if empty.

JSX also helps in cross site scripting attackes (XSS) by escaping the values embedded in jsx expression before rendering them.

Babel compiles the jsx to regular JavaScript code . Example −

const message = (
   <div className="welcome">
      Welcome !
   </div>
);

Will be converted to −

const message = React.createElement(
   'div',
   {className: 'welcome'},
   ' Welcome !'
);
raja
Published on 28-Aug-2019 11:17:20
Advertisements