JSX in React

In this tutorial we will learn about the JSX in React and how can it be useful in the React codebase. JSX is used heavily in React to create rendering components and elements which are the UI that will be produced.

What is JSX?

JSX is a type of hybrid of HTML and JavaScript. JSX stands for JavaScript XML. This helps to embed JavaScript elements like loops, conditions,

and variables in the HTML page. It looks like a template language but it can use the full extent of JavaScript.

Points to remember about JSX

  • It Follows the Lower vs upper case format to distinguish between HTML tags and React elements.
  •   Some word is reserve keyword in JavaScript such as ‘class’ we pass as an attribute to HTML tags instead we use ‘className’ for defining the class of an object.
  • In some case to provide the links we use <a href=”#”> tag and href attribute of HTML but we use <Link to=”#”> Link tag and to attribute for linking purpose.
  • The JavaScript we will be using inside JSX cannot be used directly hence we use curly braces ‘{}’ to wrap in our  JavaScript.
  • When We use the traditional inline styling to any element, component or tag we write it inside the double curly ‘{{}}’ and using camel cases for the property name   Eg:- ‘border-radius’ instead ‘borderRadius’.

Advantage of JSX

  • JSX is just HTML-like syntax
  • It allows the properties as attributes to be passed inside the elements
  • If a person is familiar with HTML then JSX is easy to learn.
  • We can easily handle the functions and can convert it them in JSX terms
  • This clean-up the code and even it is a more understandable code. EG:-
    import React from 'react';
    import ReactDOM from 'react-dom';
    
    const element = React.createElement('div',{
      className: 'welcome'
    },'Hello World')
    ReactDOM.render(
      element,
      document.getElementById('root');
    )
    //           Using JSX 
    //==================================================
    import React from 'react';
    import ReactDOM from 'react-dom';
    
    const element = <div className=''>Hello World</div>
    
    ReactDOM.render(
      element,
      document.getElementById('root');
    )

    By observing the above code we find that JSX not only shortens the code it makes more readable.

  • As we can apply condition in JSX we can use it for conditional rendering and distribute the information to show according to the user.

Example Code of JSX

Inserting Variables

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

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

In the Upcoming tutorial we will see more application of JSX and how can it be used in creating elements and components.