JSX in ReactJS

JSX is mixture of HTML and Javascript with new rules. For example:

const element = <h1>Hello, world!</h1>;

In ReactJS, we can use of mixture of HTML5, CSS, Javascript and JSX. It has been shown in following example: 

const name = 'Josh Perez';
const element = <h1>Hello, {name}</h1>;


First we create a constant (‘const’ refer to constant value) named ‘name’ and assigned to it string value. In second line, we created a JSX constant ‘element’ and assigned to it HTML + Javascript constant value {name}. Later we rendered the value of variable ‘element’ using ReactDOM. 

One JSX constant can store multiple values, such as:

const user = {
firstName: 'Harper',
lastName: 'Perez'

These values can be called in a function such as:

function name(user){
     return user.firstName + ' ' + user.lastName;

We can call this function in another constant:

const output = <h1> Hello {name(user)} </h1>;

In the end we can show this constant ‘output’ using ReactDOM: 


Now we can also put if, else conditions in the code using Javascript method: 

const user = '';

function name(user){
          return user.firstName + ' ' + user.lastName;
     else {
          return 'stranger';

Here user is empty, so it will return string ‘stranger’ in place of username. This code can be replaced in above example, to make it work. 

In react, we usually mix HTML5 and Javascript like:

const element = (
<h1 className="greeting">
Hello, world!

However in ES6 method, this can be written as: 

const element = React.createElement(
{className: 'greeting'},
'Hello, world!'

it gives exactly same output. 

Leave a Reply

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