react JSX| Basics

JSX Introduction

JSX is a syntax extension to JavaScript. It is used with React to describe what the UI should look like. JSX might seem like template language, but it comes with the full power of JavaScript.

Here is the sample code. We will explore each feature in detail in below article:

import React from 'react';  
import ReactDOM from 'react-dom';

var websiteName = 'techtrekking.net';  
var newStyle = { color:'blue'};

var myList = (<div>  
                <h1>You are on website {websiteName}</h1>
{// this is comment }
                <ul>
                    <li style={newStyle}>FIrst</li>
                    <li>Second</li>
                    <li>Third</li>
                  </ul>
              </div>)

ReactDOM.render(myList, document.getElementById('root'))  

Important Points

  • JSX is a syntax extension for JavaScript. It was written to be used with React. JSX code looks a lot like HTML.
  • A basic unit of JSX is called a JSX element.
  • JSX code can’t be ready by browser and hence it needs to be compiled before the files reaches a web browser, a JSX compiler will translate – any JSX into regular JavaScript.
    It’s similar to writing bits of HTML, but inside of a JavaScript file.
JSX Element Definition
  • JSX element can be saved in a variable, passed to a function, stored in an object or array.
var h1 = <h1>Hello world</h1>;  
Attributes in JSX
  • A JSX attribute is written using HTML-like syntax: a name, followed by an equals sign, followed by a value. The value should be wrapped in quotes, like this:
var title = <h1 id="title">Introduction to React.js: Part I</h1>;  
var panda = <img src="images/panda.jpg" alt="panda" width="500px" height="500px" />;  
  • HTML tags are always using lowercase tag names, while React components starts with Uppercase.
  • Since JSX is JavaScript, identifiers such as class and for are discouraged as XML attribute names. Instead, React DOM components expect DOM property names like className and htmlFor, respectively.
Multi-line JSX
  • You can nest JSX elements inside of other JSX elements, just like in HTML.If a JSX expression takes up more than one line, then you should wrap the multi-line JSX. i.e. opening and closings should be of same tag
var myList = (<div>  
                <h1>You are on website {websiteName}</h1>
                <ul>
                    <li style={newStyle}>FIrst</li>
                    <li>Second</li>
                    <li>Third</li>
                  </ul>
              </div>)
Using JavaScript in JSX
  • JSX is written in JavaScript file but if you need to use JavaScript variale in JSX it needs to be enclosed in curly braces “{}”
...
var websiteName = 'techtrekking.net';  
...
<h1>You are on website {websiteName}</h1>  
...
Comments in JSX
  • While writing comments we need to enclose curly braces around them “{}”.
{// this is comment }