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 }

Learning JavaScript

There are tons of material on internet to learn JavaScript and each has its own style and different target audience and it might confuse you. Also, reading online tutorials makes you think that you ‘know’ the language now but when you get down to code, you don’t recall anything and this makes learning experience very frustrating experience.

Whatever may be your intentions behind getting started with JavaScript, you can use following method to learn JavaScript.

Step#1

Start with CodeAdacemy’s interactive JavaScript tutorial. This is he best way to get your hands dirty.

Step#2

Start Reading Eloquent JavaScript. You can read this book online. But if you like to read the hard copy of the book, you can purchase it from here

You can read this book for free online at eloquentjavascript.net

Step#3

Other best online sources of learning JavaScript are as below:

Step#3

Once you are comfortable on JavaScript, please read JavaScript: The Good Parts by Douglas Crockford

Don’t just stop here, during anypoint in your learning phase you should watch following videos by Duglas Crackford.

https://www.youtube.com/watch?v=v2ifWcnQs6M&list=PL62E185BB8577B63D

https://www.youtube.com/watch?v=JxAXlJEmNMg&list=PL7664379246A246CB

create react app | Getting started with react

Create React App is the best way to start building a new React single page application. It sets up your development environment so that you can use the latest JavaScript features, provides a nice developer experience, and optimizes your app for production.

$ npm install -g create-react-app
$ create-react-app todolist

If you are using older version of Node.js and npm you might get following error message.

I am also using Ghost blogging platform so I need to use 4.8 LTS version of Node.js so I will keep my current version, but if you dont have any dependency like above, please update to latest stable version.

$ create-react-app myreactapp
Creating a new React app in /home/user/code/nodejs/myreactapp.

You are using Node v4.8.3 so the project will be boostrapped with an old unsupported version of tools.

Please update to Node 6 or higher for a better, fully supported experience.

You are using npm 2.15.11 so the project will be boostrapped with an old unsupported version of tools.

Please update to npm 3 or higher for a better, fully supported experience.  

Once installation is complete got to the newly created folder and start the application.

$ cd myreactapp
$ npm start

This will start development server and it will open a webpage on your default browser at following location.

http://localhost:3000/

This will create file structure as below: index.html provides basis div elements and index.js is primary react file which renders required components in index.js

├── package.json
├    (Node.js file structure)
├── package.json
├── public
│   ├── favicon.ico
│   └── index.html
├── README.md
└── src
    ├── App.css
    ├── App.js
    ├── App.test.js
    ├── index.css
    ├── index.js
    └── logo.svg

How to install pgAdmin on Ubuntu 16.04

pgadmin3 can be installed using following command

sudo apt-get install pgadmin3

You can invoke pgadmin3 GUI from main menu as well as by typing following command.

$ pgadmin3

From file menu, please use ‘add server’ and enter data as below:

If you facing authentication issue, please use following commands to reset the password.

$sudo -u postgres psql postgres
psql (9.6.3)  
Type "help" for help.

postgres=# password postgres  
Enter new password:  
Enter it again:  

How To Install and Use PostgreSQL on Ubuntu 16.04

PostgreSQL is a powerful, open source object-relational database system.It has more than 15 years of active development and a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness. It is one of the leading relational database used on production servers.

Ubuntu’s default repositories contain Postgres packages, so we can install these easily using the apt packaging system.

Since this is our first time using apt in this session, we need to refresh our local package index.
install the Postgres package and a -contrib package that adds some additional utilities and functionality:

$ sudo apt-get update
$ sudo apt-get install postgresql postgresql-contrib

Access PostgreSQL using following command:

$ sudo -u postgres psql

create new user. It will ask for few details while creating new user.

$ sudo -u postgres createuser --interactive
$ Enter name of role to add: test
$ Shall the new role be a superuser? (y/n) y

Create new database

$ sudo -u postgres createdb sammy

check the connection info

postgres=# conninfo  

I got following error while working with PostgreSQL

conquistador@Inspiron-3542:~$ sudo su - postgres  
postgres@Inspiron-3542:~$ psql  
psql: could not connect to server: No such file or directory  
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

Use following commands to address this error:

conquistador@Inspiron-3542:~$ sudo apt-get remove --purge postgresql-9.6  
conquistador@Inspiron-3542:~$ sudo apt-get install postgresql-9.6  

Getting started with Node.js on Digital Ocean

I have evaluated and used multiple hosting options, PaaS like openshift, Heroku and Iaas like Digital Ocean, Linode and Amazon EC2 and finally have zeroed on Digital Ocean for their simplicity, cost effectiveness and most importantly availability of rich documentations and tutorials.

Pros and Cons of PaaS IaaS has been discussed in many places so we will not go into that discussion here. This is quick refence guide for getting started with Node.js on Digital Ocean.

Digital Ocean has rich set of tutorials for getting stated with different stacks (LAMP, MEAN, crude Node.js etc). Here are set of tutorials which you can follow to get started with Node.js.

  • Get started with Initial Server Set up with Ubuntu 16.04 LTS. These steps are self explainatory and does not need any further clarification.

    • Step One — Root Login
    • Step Two — Create a New User
    • Step Three — Root Privileges
    • Step Four — Add Public Key Authentication
    • Step Five — Disable Password Authentication
    • Step Six — Test Log In
    • Step Seven — Set Up a Basic Firewall
  • Install Node.js. This step will install latest Node.js. Some times you might need some specific version of Node.js. For example, Ghost blogging platform wont run of latest Node.js version as its not yet supported. Ghost official website recommendeds >=4.2 <5.* (Node v4 argon LTS). Please check this tutorial if you want to install specific version of Node.js.

  • Now basic server set up is done and Node.js is installed, now you need nginx server. Follow how to install nginx tutorial to install ngnix.

  • Now you are all set. Follow how to set up Node.js tutorial to set up very basic Node.js application. Once you have done with this step, to get more comfortable with Node.js on ubuntu server, follow creating you first Node.js tutorial . This will give you more hands on and will increase your comfort level.

  • Setting up domain on Digital Ocea is super simple. Simple follow this tutorial to get it done.

    I faced an issue with domains. My website was working perfectly wine with https://example.com but it was not working for https://www.example.com. If you also face this issue, please go to Droplets->Add Domain–>Manage Domains and add a ‘A’ record as ‘www’ (without quotes), select your droplet and click on create record. This will resolve your issue.

  • (optional) You can make your website secure by following this tutorial.

  • (optional) If you are getting started and would like to host multiple Node.js websites on the single droplet, follow how to set up multiple virtual blocks tutorial.

Adding Syntax Highlighter to Ghost Blog

Using newer things has its own set of disadvantages and ghost blogging platform is no exception. Ghost does not have efficient coding markup tools. They do have coding style which looks like below:

code Inline Code Ctrl/⌘ + Shift + K

Disadvantage of this way to syntax highlighter is that

  • It does not differentiate between syntax of different lanaguges.

  • formatting is very basis. When I was searching for better ways of doing syntax highlighting, I came across a faq on ghost blog which suggested to use prism.js for syntax highlighting.

This is one of the simplest tool that I have came across and you can set it up in few minutes.

Step#1
Download prism.js and prism.css from downaload page..
Before downloading these files, you need to select theme and list of languages to which you need this markup.

I have selected Okaidia theme and all languages (you never know which language you might need to refer, specially for a tech blog)

Step#2
Copy prism.js and prism.css files in following folder respectively

content/themes/theme-name/assets/js  
content/themes/theme-name/assets/css  

Step#3
Now we need to include prism.js and prism.css in default.hbs file of whichever theme you are using.
Include prims.css file in head section, just below other CSS files

<link rel="stylesheet" type="text/css" href="{{asset "css/prism.css"}}" />  

Include prism.js file in footer section just before end of body section.

<script type="text/javascript" src="{{asset "js/prism.js"}}"></script>  

This tool has some limitations, as you can see, above line is not rendered properly as html. This is because of double double-quotes. This works well if we remove double-quotes.

<script type="text/javascript" src="{{asset 'js/prism.js'}}"></script>  

Step#4
Deploy these updated files on your ghost server and you are all set. Language markup can be done as below:

  • language-javascript
  • language-sql
  • language-css
  • language-bash
  • language-html

Installing Node.js and NPM on Ubuntu 16.04 LTS

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

In this article we will look at how to install nodejs and npm on ubuntu 16.04 LTS.

Step#1
Following commands can be used to check if nodejs and npm is installed on your machin. If its already installed,you will get the installed versions.

$ npm -v
$ node -v

Step#2
If Node.js is not installed, we can install it by using Node.js PPA provided by official site. As a prerequisite, we need to install python-software-properties package if not installed already.

$ sudo apt-get install python-software-properties
$ curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -

Above command will install Node.js versoon 7.X. if you need any previous version, lets say Node v4.8.0 (LTS), please use following command.

$ curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -

Step#3
After adding PPA files, your required Node.js version can be installed using following command.

$ sudo apt-get install nodejs

Once installation is completed, versions can be checked using following commands

$ npm -v
$ node -v

These commands will let you know the latest versions.

Once Node.js has been installed, please check article, creating your first Node.js application to get started

Creating Your First Node.js Application

Follow these instructions to create your fist nodejs application is less than 5 mins.

I assumed you already have nodejs and npm installed on your machine, if not please follow “How to install nodejs” tutorial and come back here after installation is completed.

Step#1
Open command promt in admin mode and go to the folder where you want to create your first nodejs project. Install express and express-generator using following commands.

npm install express –save  
npm install express-generator –save`  

Step#2
There are multiple templating option that you can choose such as handlebars, pug, hogan but I choose ejs as its very user friendly and it does not have steep learning curve. Create your first nodejs app by using following command

express --view=ejs myapp  

Step#3.
cd into new folder and install node packages by using following commands

cd . && npm install  

Step#4
And you are all set. Start your nodejs application by using following command. This will start your application in debug mode.

SET DEBUG=myapp:* & npm start  

If you don’t want to start application in debug mode you can just simple start Node.js app using following command

npm start  

This will get you started with nodejs under 5 minutes. This will create your bare minimum nodejs application. now you can go ahead and do any further front end development that you need.

Our nodejs application is just like steel frame, it just send you one simple webpage, nothing else, we can enhance it further to create data feed api and other complex features. We will look at step by step guide of these at later stages.

How to add Google Analytics to Ghost Blog

Google Analytics is one of the most popular and powerful tool, following article explains how to use add Google Analytics to Ghost Blog. There are two methods to do so.

Adding Google Analytics using Code injection

Follow these steps and you are all set.
1. Add your website to https://analytics.google.com and get the unique code.
2. Login to Ghost Admin section and go to Settings –> Code Injection

3.Insert your code in this section and click “Save” and you are done.

Adding Google Analytics to Ghost theme

  1. Add your website to https://analytics.google.com and get the unique code.
  2. Go to ..contentthemes
  3. Find default.hbs file and open it in your favorite a text editor. I use brackets.
  4. Add it just below the {{ghost_head}} and above .

    5.Restart the ghost and you are all set.