Introduction to JSX In React.Js

JSX is basically syntax extension to JavaScript. We use it with React.js to describe what UI should look like. It looks like HTML but actually, it is not. It comes with the full power of JavaScript.

Introduction to JSX in React.Js
 
  const element = 

Tutorial Funda

;

Look at the above code syntax. It’s not the HTML it’s a JSX. JSX produces React elements. Babel compiles JSX into React elements calls. Then it further converts to the object called “React Elements“. Let’s look at the example.

How JSX Converts into React Elements

This is a JSX Code:

 
  const element = (
   

Tutorial Funda

);

This React Element Call Code (Converted From JSX)

 
  const element = React.createElement(
  'h1',
  'Tutorial Funda'
);

This is React Element Object (Converted From React Element Call)

 
   const element = {
   type: 'h1',
   props: {
     children: 'Tutorial Funda'
   }
  };

This is how JSX converts into React Elements Objects. React uses these objects to construct DOM and keep it up to date.

What You Can Do with JSX?

1] You can use any valid JavaScript Expression inside JSX. Example Below.

In JSX, You can use any valid JavaScript expression with curly braces. For example, {10 + 10}, {user.firstName}, or {formatName(user)} these all are valid JavaScript expressions.

 
  const user= 'Suraj';
  const element = 

Hi, {user}

; ReactDOM.render( element, document.getElementById('root') );

2] JSX itself you can use as an Expression

JSX actually gets converted into JavaScript. So you can use JSX inside if-else, for loop etc. Example Below.

 
    function getHello(user) {
    if (user) {
      return 

Hello, {getName(user)}

; } return

Hello, Unknown.

; }

3] Attributes with JSX

You can use quotes for string values and curly braces for Javascript expression.

  const divelement = 
; const imgelement = ;

Note: React DOM uses camelCase property naming convention like tabindex becomes tabIndex.

4] Child elements with JSX

JSX tags can contain as many of child tags it can.

   const divelement = (
    

Hi!

What a Surprise!

);

5] Auto prevention of Injection Attacks

JSX automatically prevents injection of any malicious input. Everything is converted to a string before being rendered. It prevent XSS (cross-site-scripting) attacks.

We hope you Basic information about JSX. In upcoming articles, we will look deeper in JSX and some important topics in React.Js.

Admin

Tutorial Funda will keep you updated with the latest Programming Languages, Software Tools and related technologies used in Software Development.

Leave a Reply

Your email address will not be published. Required fields are marked *