Explaining JSX with some examples

We all have heard of JSX. Lets explain it with some examples. First lets break the word down. JSX is a Javascript extension. It actually extends the language. It more looks like HTML or XML when you write it. But it is naturally Javascript. 

For browsers to understand it, it needs to be compiled with a compiler like Babel. Ket us write some JSX examples and explain it better:

const element =

This is JSX

;

You can clearly see the syntax looks like a mix of HTML and Javascript.It is not a template language. It comes with the full power of Javascript.

React and JSX

React embraces JSX to be used to define Elements and Components. It looks like rendering logic is mixed with UI logic. The fact is in react, logic and UI are not seperate as files. They are seperate as concerns by using and defining components.

Although react does not require JSX. but it is easy to use and better to read so most react developers tend to use JSX in their applications.

JSX Examples 

Lets see how this code renders in react:


const element = (  

  Hello, world!  

);


This is identical to this code in react:


const element = React.createElement(   ‘h1’,   {className: ‘greeting’},   ‘Hello, world!’ );


Babel compiles JSX down to React.createElement() calls.As you can see, class attribute is called className in camel case here. This code actually creates an object like this:


const element = {   type: ‘h1’,   props: {     className: ‘greeting’,     children: ‘Hello, world!’   } };


This object is called an element which describes what is to be shown in the UI.

Now check out this JSX code:


const name = ‘Azadeh’;

const element =

Hello, {name}

;


We declare a variable called name and then use it inside JSX by wrapping it in curly braces. You can put any vald Javascript expression inside curly braces in JSX. Functions , objects, objects properties.

Also we can write JSX inside functions.Here we used JSX to return the value which is an expression itself.


function getGreeting(user) {   if (user) {     return

Hello, {formatName(user)}!

;   }   return

Hello, Stranger.

; }


Next

In the next articles , we will learn more about JSX and break it down to details. We will write more elements and components in react to explain JSX syntax clearly.

© 2020
Azadeh Faramarzi

This site is created and maintined by Azadeh Faramarzi , A passionate developer, sport and code lover who loves to share and write when she has some time.