JSX Expressions

  • Overview of JSX
  • Creating HTML/XML elements/nodes with JSX
  • JSX Attributes / props
  • Comments in JSX
  • Expressions with
    • Arithmetic operators
    • Ternary Operators
    • Comparison Operators
    • Assignment Operators

Overview of JSX

  1. The full-form of JSX is Javascript and XML, e., simply JSX = Javascript + XML/HTML
  2. JSX is a simple syntax with a combination of HTML/XML tags with Javascript
  3. React used JavaScript expressions within curly braces “{ <expression> }”. We can put any type of JavaScript expression in the curly braces inside JSX.
  4. React can perform only one-way binding, to perform two-way binding we need to use React component’s state and props/ Event listeners.
  5. Each React Element is like a real kind of javascript object which can be either stored in a variable or can be used throughout the program.
  6. After coding in JSX pages no need to precompile the code, the JSX file will be automatically compiled and generates JavaScript syntax in the browser if the JSX is written in ES5, but if the JSX is written in ES6 then this should be pre-compiled by either Babel/ Typescript e.,
    1. Babel
      1. Babel is a process that transforms your JSX code (ES6) into Javascript (ES5) which is browser understandable code.
      2. Bable engine abstracts the Reacts ES6 JSX syntax and recreates that into ES5 syntax, for exampleCode written in ES6 syntax

        Now Babel converts it into ES5 syntax as follows
      3. We will install the following dev dependencies:
        1. babel-loader: babel module loader
        2. babel-core: the core transpiler used for transporting ES2015 and JSX code
        3. babel-preset-es2015: ES6/ES2015 support
        4. babel-preset-react: React/JSX support
        5. babel-preset-stage-2: babel preset for some extra features such as destructuring
        6. webpack: for bundling our packages for distribution and managing dependencies
        7. webpack-dev-server: our development server
      4. Babel 6 doesn’t supports the bundle.js to transform the ES6 to ES5, so for that we need to use Babel older version (i.e., 5.8.X) to transform the JSX code to be pre-compiled and generates the javascript and saved into bundle.js (this can be renamed, and this code is rendered int0 browser) by using webpack.config.js.
    2. Typescript
      1. Typescript is a language the can be either written in ES5/ ES6. Typescript has its own compiler tsc(typescript compiler) to pre-compile the ES6 syntax to ES5.
      2. We will install the following dev dependencies:
        1. ts-loader: typescript module loader to build .tsx
        2. typescript: language for programming in react (either in ES5/ ES6 syntax)
        3. webpack: for bundling our packages for distribution and managing dependencies
        4. webpack-dev-server: our development server
        5. This also uses the bundle.js where after compiling will be saved here with ES5 syntax.
        6. React with Typescript will be written in special extension files i.e., .tsx.               Ex: sample.tsx
  7. Within a JSX syntax we can perform both Data-Binding and Event Binding.

 

Creating HTML/XML Elements/nodes in JSX:

For creating HTML/XML nodes in JSX React provides a pre-defined function.

Syntax:

Where type, props and children are the arguments for function React.createElement( ).

  1. Type (string / React.createClass( ) ):   This is a mandatory argument. Type argument can be a string value (or) it can be a ReactComponent instance.
  1. Props (null / object):   This is an optional argument, where we can pass null (or) an object
  1. Children (null / string / React.createClass( ) / React.createElement( ) ):  This is an optional argument, we can either pass null value (or)  string value (or) React.createElement (or)  React.createClass instance.

 

ReactDOM.render( ):  For rendering react nodes into DOM, React provides function ReactDOM.render( )  from “react-dom” module.

  1. Rendering in react is also possible on server-side withrenderToString( ).
  2. If a change is made (or) a new child nodes has been added to DOM element, ReactDOM will only update the child nodes which is called Re-Rendering.

Ex: Creating <ul> tag with nested <li> tags

 

JSX Props: We have already know the syntax for creating custom HTML elements, second parameter props can be passed as an object/null.

  1. Props are nothing but HTML attributes that are passed as name-value pairs.
  2. Props are generally used for passing inputs to the component.
  3. Props can be passed to nodes in a Component (or) directly to the Component.
    1. Props that are used for nodes/elements are called Node Props/Attributes.
    2. Props that are used for Components are called Component Props/Attributes.
  4. Props creating may vary when using Typescript with React (TSX) with Formal React (JSX). When using TSX must define the type of the Props when creating nodes.

 

Using Typescript with React (TSX)

 

Comments in JSX:

  • Comments in jsx use //  and /* */

Ex:

 

Javascript Expressions:

To make use of Javascript statements with JSX, React provides a syntax using curly braces “{  }”.

Note: Follow the steps for setup ASP.NET MVC application in React Introduction.

Example:

Step1: Open your ASP.NET MVC application à  src/expressions.tsx (Creating file expressions.tsx in src )

Note: Run webpack.config.js , because unless it is running in the background the changes which we have done will not be reflected in the bundle.js. So make sure that while making any changes in .tsx files, webpack.config.js is running in the background.

File: expressions.tsx

File: index.cshtml

File: webpack.config.js

Change the entry point to expressions.tsx

Output:

Sum of 2+3 = 5

 

JSX Expression with Arithmetic Operators:

File: src/expressions.tsx

Note: Run webpack.config.js , because unless it is running in the background the changes which we have done will not be reflected in the bundle.js. So make sure that while making any changes in .tsx files, webpack.config.js is running in the background.

 

JSX Expression with Ternary Operators:

Javascript Ternary Operators ( ? : ) returns two expression depending on condition

Ex:

var a = true;

var result = a == true ?’yes’ : ‘no’;

File: expressions.tsx

Modify the render( ) as follows

Note: Run webpack.config.js , because unless it is running in the background the changes which we have done will not be reflected in the bundle.js. So make sure that while making any changes in .tsx files, webpack.config.js is running in the background.

 

JSX Expression with Comparison Operators

Comparison operators are used to compare any two values / variables

List of the comparison operators

 

 

JSX Expression with Assignment Operators:

Assignment operators just assigns the value to a variable.

Ex:

 

Complete Example

Note: Run webpack.config.js , because unless it is running in the background the changes which we have done will not be reflected in the bundle.js. So make sure that while making any changes in .tsx files, webpack.config.js is running in the background.

 

Introduction to React JS

  1. What is React JS?
  2. What are the advantages of React?
  3. Limitations of React

 

What is React?

  • React is a front-end JavaScript library. Let me explain you in simple language with few key features of React.

Eliminating Redundancy:

  • While working on any application which uses HTML as Views, you might have a situations where you just copy and paste the same code at many places. Which is called as Code Redundancy.
  • So at this situation did you ever thought that how would if I can reuse this HTML code at multiple places.

Page1.html

Page2.html

If you are in this situation then how would if there is a common HTML for both page1 and page2.

Page1.html

Page2.html

How about this, awesome right!

Yes of course if we could do this there will be no more HTML code redundancies in the application.

 

Reuse UI Components:

  • If we can reduce the code redundancies using custom HTML tags, this is nothing but creating Reusable UI Components like <app-head></app-head>.
  • According to React documentation “React is a library for building reusable UI components which presents data that changes over time”.
  • Here the React Components comes into picture.
  • Component:
    • React application is all about components, the entire application will be divided into several Component segments.
    • One component can be nested with other component.
    • Components can be created in two ways,
      • Using var Component = CreateClass({ })
      • Using ES6 standards with Class keyword, class Component extends React.Component<{},{}>{  }

 

Ex:Using ES6 Syntax

Ex: Using ES5 Javascript Syntax

Easy Data-Binding:

  • This is one of the most important thing in React which is called as “Data-Binding”.
  • React can do only one-way binding using its interpolation “{ <expression> }”.
  • Here the JSX comes into picture, where JavaScript + XML = JSX.
  • JSX:
    • React used JavaScript expressions within curly braces “{ <expression> }”. We can put any type of JavaScript expression in the curly braces inside JSX.
    • Each React Element is like a real kind of javascript object which can be either stored in a variable or can be used throughout the program.
    • After coding in JSX pages no need to precompile the code, the JSX file will be automatically compiled and generates JavaScript syntax in the browser.

Example: Here I’ve used TSX instead of JSX, that’s why syntax while importing the libraries might look different.

Instead we can use, in JSX files

In TSX files,

 

 

Advantages of React:

  • Reusability of the UI code.
  • Eliminating code Redundancies (common code)
  • Familiar Syntax such as using class, extends, implements, interface keywords which are used for programming in most of the familiar languages like Java and .Net framework ,
  • The virtual DOM makes the testing simpler for the testers.
  • React can be used with most of the frameworks, because this is used only as a View Layer. Just we can replace the View Layer in any project with React UI Components. And it’s compatible with any Framework.
  • This is a light-weight library.
  • JSX syntax makes the developers feel free to use react i.e., Developers can use both javascript and HTML in a JS / JSX / TSX (typescript + XML) files with in a component. Where the developers will write the business logics in the component class, and the view part in the component’s templatee., with in the render ( ).
  • React can be written in
    • Javascript (.js) –   ES5 syntax
    • React’s recommended (.jsx) – Both ES5 and ES6 syntax
    • Typescript (.tsx) files. –  Both ES5 and ES6 syntax

 

Limitations:

  • React is just a library, because of that to develop an application React is just isn’t enough.
  • It doesn’t have its own routing, sevices etc… Because it is not a framework.
  • React has failed in competing with most of the advanced frameworks like Angular.
  • If someone asks why only React? There would be no perfect answer. Because Angular Framework can perform all the operations that React can do.

React JS setup using ES6 with .tsx files in Visual Studio

Download Source Code

When i’m a beginner to React i’ve faced many issues in making setup with Visual Studio. As i’ve found that there are many ways to write React code.

  • Can be written in Js  files using ES5
  • Can be written in JSX files using ES5
  • Can be written in TSX files using ES6

tsx –> ts (typescript) + jsx ( javascript and xml)

Where most of the tutorials were providing setups with JSX/JS using ES5.  Now i’ll show you how to setup in your local environment Visual Studio using ES6 with TSX (typescript syntax).

Step 1: Install Npm

  • To install the React Js we need Node Js environment setup.
  • js development environment can be setup in Windows, Mac, Linux and Solaris. The following tools/SDK are required for developing a Node.js application on any platform
    • js
    • Node Package Manager (NPM)
  • NPM (Node Package Manager) is included in Node.js installation since Node version 0.6.0., so there is no need to install it separately.
  • To Install Node visit Node.js official web site https://nodejs.org. It will automatically detect OS and display download link as per your Operating System.Click on Download and install the latest version.
  • Once you install Node.js on your computer, you can verify it by opening the command prompt and typing node –version. If Node.js is installed successfully then it will display the version of the Node.js installed on your machine, as shown below.

Step 2: Create ASP.Net Web Application

  • Open Visual Studio FileNewProject
  • Select->”Web Template”->select the ASP.Net Web Application->Click OK
  • In the “New ASP.NET MVC Project” dialog, Select the MVC Template->Click OK
  • Goto->Tools-> Options –> Projects and Solutions –> Select External Web Tools->Move $(PATH) to above the $(DevEnvDir)->Click Ok

Step 3: Create package.json file and install the required packages using npm commands. Open Command prompt and Goto your project directory and run command

 

2. Now provide a name using lower case. And you can just click enter and say Yes.

  •  Install webpack

  • Install webpack-dev-server

  • Install react and react-dom. React and ReactDOM are generally used together. ReactDOM is a package for working with the DOM

  • Now we need typescript and ts-loader to load and build .tsx files

File: package.json

 

Step 4:  Download React Quick Start files 

Go to the following link and download React Quick Start files

Step 5: Copy required folder into your ASP.Net Web Application

  • Copy dist, typings and src folders  from quick start files and paste them in the project.
  • dist —> This folder has bundle.js which will be always update by using Web Pack Task Runner.
  • typings –> This is used to provide typescript intellisence to .tsx files
  • src –> This is the folder where we create .tsx files and do some coding part.
  • When we do any changes in .tsx files make sure that you run the Web Pack Task Runner. Unless the changes will not get updated in bundle.js.

Step 6: Copy webpack.config.js in the project directory.

  • In order to use external modules webpack.config.js must be included with resolve:{extensions: [‘.ts’, ‘.tsx’, ‘.js’, ‘.json’]}.
  • entry –> You can setup startup file here.
  • output: To direct the changes in .tsx to bundle.js.
  • module: Setting up the loaders that are used. Here we are using ts-loader. 

File: webpack.config.js

 

Step 7:  Copy tsconfig.json and typings.json files from quick start and paste them in the project.

Step 8: Install WebPack Task Runner .

  • Now right click webpack.config.js –> open Task Runner Explorer
  • Click on Run-Development / Watch-Development.
  • If any error in the we can l0ok at the error from Run-Development / Watch-Development.

Step 9: Add div tag in the index.cshtml with an id attribute. Refer that id in src –> index.tsx.

File: Views –> Home –> index.cshtml 

File: src/index.tsx

Output: