/    /  ReactJS- React JSX

React JSX

 

As we learned earlier, React JSX is an extension of JavaScript. It enables app developers to create virtual DOM using XML syntax. It compiles down to pure JS-JavaScript (React.createElement function() calls). Since it compiles JavaScript, and it can be used inside any valid JavaScript code. For example, the below codes are perfectly valid.

 

  • Assign to a variable.
            var greeting = <h1>Hello React!</h1>

 

  • Assign to a variable based on a condition.
            var canGreet = true;
            if(canGreet) {
                        greeting = <h1>Hello React!</h1>
            }

 

  • used as return value of a function
            function Greeting() {
            return <h1>Hello React!</h1>
  
            }
            greeting = Greeting()

 

  • used as argument of a function.
            function Greet(message) {
            ReactDOM.render(message, document.getElementById('react-app')
            }
            Greet(<h1>Hello React!</h1>)

 

Expressions:

JSX supports expression in pure JavaScript(JS) syntax. The expression has to be enclosed inside the curly braces, { }. The expression can contain all variables available in the context, where the JSX is defined. Let us create simple and easy JSX with expression.

Example:

<script type="text/babel">
   var cTime = new Date().toTimeString();
   ReactDOM.render(
      <div><p>The current time is {cTime}</p></div>,
      document.getElementById('react-app') );
</script>  

Output:

The Current time is 21:19:56 GMT+0530(India Standard Time)

 

Functions:

JSX supports user-defined JavaScript functions. Function usage is similar to expression. Let us create a simple/easy function and use it inside JSX.

Example:

<script type="text/babel">
   var cTime = new Date().toTimeString();
   ReactDOM.render(
      <div><p>The current time is {cTime}</p></div>,
      document.getElementById('react-app')
   );
</script>

Output:

The Current time is 21:19:56 GMT+0530(India Standard Time)

 

Attributes:

JSX supports HTML like attributes. All HTML, CSS tags and their attributes are supported. Attributes have to be specified using camelCase convention (and it follows JavaScript DOM API) instead of the normal HTML attribute name. For example, a class attribute in HTML has to be defined as className. The following are a few other examples −

  • htmlFor instead of for
  • tabIndex instead of tabindex
  • onClick instead of onclick

Example: 

<style>
   .red { color: red }
</style>
<script type="text/babel">
   function getCurrentTime() {
      return new Date().toTimeString();
   }
   ReactDOM.render(
      <div>
         <p>The current time is <span className="red">{getCurrentTime()}</span></p>
      </div>,
      document.getElementById('react-app')
   );
</script>

Output:

The Current time is 22:36:55 GMT+0530(India Standard Time)