Sunday 5 January 2020

Introduction to JSX in ReactJs


JSX

JSX stand for JavaScript XML and it is JavaScript syntax extension used by react .
JSX is an XML/HML -like syntax used by reactjs. It is neither JS nor HTML/XML. it compiled and transform JSX code into standard javascript code. 

JSX code is combination of javascript and react DOM element. It is faster because it perform optimization while compiler the code in to js.


Let us see a sample JSX code:
var ele = <h1>This is sample JSX</h1>;


import React from 'react';

class MyApp extends React.Component {
   render() {
      return (
         <div>
            <h1>Hello World!</h1>
            
         </div>
      );
   }
}
export default MyApp;


Custom attributes in JSX


We can create custom attribute in regular JSX code. we need to use 'data' prefix. data_myAttribute as an attribute element of react jsx.

import React from 'react';

class MyApp extends React.Component {
   render() {
      return (
         <div>
            <h1>Header</h1>
            <h2>Content</h2>
            <p data_myAttribute="data_val">This is another content</p>
         </div>
      );
   }
}
export default MyApp;

JSX Expression

If we write any expression in react then we will use expression like below
var ele = <h1>{1+1}</h1>;
We can not use if else statement in the react like other technology syntax. In react we have to use ternary operator expression like below

var i=0;
var ele =<h1>{i==1?'True':'False'}</h1>;

For any style object we can use camleCase to write the css.

var ele = <p style={fontSize:"10px"}>This is sample JSX</p>;

Comment statement in JSX

{//this is line comment};
{/* this is multiple line comment*/}

Naming Convention

HTML tags always use lowercase tag names, while React components start with Uppercase.
Note − You should use className and htmlFor as XML attribute names instead of class and for.
This is explained on React official page as −
Since JSX is JavaScript, identifiers such as class and for are discouraged as XML attribute names. Instead, React DOM components expect DOM property names such as className and htmlFor, respectively.




No comments:

Post a Comment