DEV Community

Margia Sultana
Margia Sultana

Posted on

React JSX

JSX is simply a syntax extension of JavaScript.It stands for JavaScript XML.JSX is an HTML-like syntax that we can use with React to make it easier and more intuitive to create React components. It is only purpose is to make it easier to create React components.

Benefits of using JSX:
It is type-safe, and most of the errors can be found at compilation time. It makes it easier to create templates. It is faster than regular JavaScript because it performs optimization while translating the code to JavaScript.

JSX Expression:
JSX supports expression in pure JavaScript syntax. A JSX expression starts with an HTML-like open tag and ends with the corresponding closing tag. JSX tags support the XML self-close syntax so we can optionally leave the closing tag off. JSX expressions evaluate to ReactElements.

Function:
JSX supports user-defined JavaScript functions. Function usage is similar to expression.

Attributes:
JSX supports HTML like attributes. All HTML tags and their attributes are supported. JSX uses camelcase naming convention for attributes rather than the standard naming convention of HTML such as a class in HTML becomes className in JSX because the class is the reserved keyword in JavaScript. We can also use our own custom attributes in JSX. For custom attributes, we need to use data- prefix.
Example:

import React, { Component } from 'react';  
class App extends Component{  
   render(){  
     return(  
         <div>  
             <h1>react JSX</h1>  
             <h2>JSX atributes</h2>  
             <p demo-Attribute = "demo">This is custom attribute.</p>  

         </div>  
      );  
   }  
}  
export default App; 
Enter fullscreen mode Exit fullscreen mode

In this example, we have used a custom attribute demo-Attribute as an attribute for the

tag. In JSX, we can specify attribute values in two ways.

  1. As String Literals:
    We can specify the values of attributes in double quotes.

  2. As Expressions:
    We can specify the values of attributes as expressions using curly braces {}.

JSX Comments:
JSX allows us to use comments that begin with /* and ends with */ and wrap them in curly braces {} just like in the case of JSX expressions.

JSX Styling:

React always recommends using inline styles. To set inline styles, you need to use camelCase syntax. React automatically allows appending px after the number value on specific elements.

Example:

import React, { Component } from 'react';  
class App extends Component{  
   render(){  
     var myStyle = {  
         fontSize: 80,  
         color: 'black  
      }  
      return (  
         <div>  
            <h1 style = {myStyle}>JSX styling</h1>  
         </div>  
      );  
   }  
}  
export default App;  
Enter fullscreen mode Exit fullscreen mode

Top comments (0)