Unit5 1
Unit5 1
Introduction
Angular is a client-side JavaScript framework that was specifically designed to help
developers build SPAs (Single Page Applications) in accordance with best practices
for web development.Single-page application (or SPA) are applications that are
accessed via a web browser like other websites but offer more dynamic interactions
resembling native mobile and desktop apps. The most notable difference between a
regular website and SPA is the reduced amount of page refreshes. SPAs have a
heavier usage of AJAX- a way to communicate with back-end servers without doing
a full page refresh to get data loaded into our application. As a result, the process of
rendering pages happens mostly on the client-side.
o Iterators
o For/Of loops
o Reflection
o Improved dependency injection – bindings make it possible for
dependencies to be named
o Dynamic loading
o Asynchronous template compilation
o Simpler Routing
o Replacing controllers and $scope with components and directives – a
component is a directive with a template
• Support reactive programming using RxJS
Features of Angular
Cross Platform
• Progressive web apps: It uses modern web platform capabilities to deliver
an app-like experience. It gives high performance, offline, and zero-step
installation. So, working with Angular is pretty much easy.
• Native: Builds native mobile apps with strategies using Ionic Framework,
NativeScript, and React Native.
• Desktop: Create desktop-installed apps across Mac, Windows, and Linux
using the same Angular methods you’ve learned for the web plus.
Speed and Performance
• Code generation: Angular turns your templates into code that’s highly
optimized for JavaScript virtual machines, giving you all the benefits of hand-
written code with the productivity of a framework.
• Universal: Any technology can be used with Angular for serving the
application like node.js, .NET, PHP and other servers.
• Code splitting: Angular apps load quickly with the new Component Router,
which delivers automatic code-splitting, so users only load code required to
render the view they request.
•
Productivity
• Templates: Quickly create UI views with simple and powerful template
syntax.
• Angular CLI: Command line tools: Can easily and quickly start building
components, adding components, testing them, and then, instantly deploy
them using Angular CLI.
• IDEs: Get intelligent code completion, instant errors, and other feedback in
popular editors and IDEs like Microsoft’s VS Code.
Modules
Angular apps are modular and to maintain modularity, there exists Angular
modules or NgModules. Every Angular app contains at least one Angular
module, i.e. the root module. Generally, it is named as AppModule. The root
module can be the only module in a small application. Most of the apps have
multiple modules. A module is a cohesive block of code with a related set of
capabilities which have a specific application domain or a workflow. Any angular
module is a class with @NgModule decorator.
Decorators are functions that modify JavaScript classes. Decorators are basically
used for attaching metadata to classes so that, it knows the configuration of those
classes and how they should work. NgModule is a decorator function that takes
metadata object whose properties describe the module. The properties are:
• declarations: The classes that are related to views and it belong to this
module. There are three classes of Angular that can contain
view: components, directives and pipes. We will talk about them in a while.
• exports: The classes that should be accessible to the components of other
modules.
• imports: Modules whose classes are needed by the component of this
module.
• providers: Services present in one of the modules which is to be used in the
other modules or components. Once a service is included in the providers it
becomes accessible in all parts of that application
• bootstrap: The root component which is the main view of the application.
This root module only has this property and it indicates the component that is
to be bootstrapped.
Template of root module (i.e. src/app/app.module.ts):
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
imports:[ BrowserModule ],
providers: [ BookList ],
declarations: [ AppComponent ],
exports: [],
bootstrap: [ AppComponent ]
})
export class AppModule { }
A root module generally doesn’t export it’s class because as root module is
the one which imports other modules & components to use them. The AppModule is
bootstrapped in a main.ts file, where the bootstrap module is specified and inside the
bootstrap module, contains the bootstrap component.
Angular libraries
Angular gives a collection of JavaScript modules (library modules) which provide
various functionalities.
Each Angular library has @angular prefix, like
@angular/core,
@angular/compiler,
@angular/compiler-cli,
@angular/http,
@angular/router.
using the npm package manager the libraries can be installed and import parts of
them with JavaScript import statements.
Example:
import { Component } from '@angular/core';
Components
A component controls one or more section on the screen called a view. For example,
for a movie list application, you can have components like App Component (the
bootstrapped component), Movielist Component, Movie Description Component, etc.
Inside the component, component’s application logic is defined i.e. how does it
support the view—inside a class.
The class interacts with the view through an API of properties and methods.
Every app has a main component which is bootstrapped inside the main module, i.e
AppComponent.
Templates
A template is a form of HTML tags that tells Angular about how to render the
component.
A template looks like regular HTML, except for a few differences.
Example
<app-navbar></app-navbar>
<div class ="container">
<flash-messages></flash-messages>
<router-outlet></router-outlet>
</div>
Metadata
Metadata tells Angular how to process a class.
To inform Angular that MovieList Component is a component, metadata is attached
to the class.
In TypeScript, attach metadata by using a decorator.
Here is the @Component decorator, which identifies the class immediately below it
as a component class. The @Component decorator takes the required configuration
object which Angular needs to create and present the component and its view.
The most important configurations of @Component decorator are:
• selector: Selector tells Angular to create and insert an instance of this
component where it finds <app-movies> tag. For example, if an app’s HTML
contains <app-movies></app-movies>, then Angular inserts an instance of the
MovieListComponent view between those tags.
• templateUrl: It contains the path of this component’s HTML template.
• providers: An array of dependency injection providers for services that the
component requires. This is one way to tell Angular that the component’s
constructor requires a MovieService to get the list of movies to display.
The metadata in the @Component tells Angular where to get the major building
blocks to be specified for the component. The template, metadata, and component
together describe a view.
Data Binding
If framework is not used, data values are to be pushed into the HTML controls and
turn user responses into some actions and value updates.
Writing such push/pull logic is tedious, error-prone, and a nightmare to read. Angular
supports data binding, a mechanism for coordinating parts of a template with parts of
a component.
Add binding markup to the template HTML and inform Angular how to connect both
sides.
Each form has a direction — to the DOM, from the DOM, or in both directions.
<li> {{movie.name}}</li>
<movie-detail [movie]="selectedMovie"></movie-detail>
<li (click)="selectMovie(Movie)"></li>
In two-way binding, a data property value flows to the input box from the component
as with property binding. The user’s changes also flow back to the component,
resetting the property to the latest value, as with event binding. Angular processes all
data bindings once per JavaScript event cycle, from the root of the application
component tree through all child components.
Data binding plays an important role in communication between a template and its
component. Data binding is also important for communication between parent and
child components.
Directives
• Angular templates are dynamic. When Angular renders them, it transforms the
DOM according to the instructions given by directives.
• A directive is a class with a @Directive decorator. A component is a directive-
with-a-template; a @Component decorator is actually a @Directive decorator
extended with template-oriented features.
• While a component is technically a directive, components are so distinctive
and central to Angular applications that this architectural overview separates
components from directives.
• Two other kinds of directives exist: structural and attribute directives.
• Directive tends to appear within an element tag as attributes do, sometimes
by name but more often as the target of an assignment or a binding.
• Structural directives alter layout by adding, removing, and replacing elements
in DOM.
*ngFor tells Angular to retrieve one <li> per movie in the movies
*ngIf includes the MovieDetail component only if a selected movie exists.
<input [(ngModel)]="movie.name">
Angular has a few more directives that either alter the layout structure (for example,
ngSwitch) or modify aspects of DOM elements and components (for example,
ngStyle and ngClass).
Custom directives can also be created.
Services
Service is a broad category encompassing any value, function, or feature that the
application is in need of.
A service is typically a class with a well-defined purpose.
Anything can be a service.
Examples include:
• logging service
• data service
• message bus
• tax calculator
• application configuration
Angular has no definition of a service.
There is no service base class, and no place to register a service.
Yet services are fundamental to any Angular application.
Components are the consumers of services.
Environmental Setup
Nodejs
NPM (Will be installed along with NodeJs)
To install angularjs
npm install –g @angular/cli
To check the installation versions run the following in command line mode.
node –v
npm –v
ng -v
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
}
Assets
You can save your images, js files in this folder.
Environment
This folder has the details for the production or the dev environment. The folder
contains two files.
• environment.prod.ts
• environment.ts
Both the files have details of whether the final file should be compiled in the
production environment or the dev environment.
The additional file structure of Angular 4 app folder includes the following −
favicon.ico : This is a file that is usually found in the root directory of a website.
index.html : This is the file which is displayed in the browser.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>HTTP Search Param</title>
<base href = "/">
<link href = "https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<link href = "https://fonts.googleapis.com/css?family=Roboto|Roboto+Mono"
rel="stylesheet">
<link href = "styles.c7c7b8bf22964ff954d3.bundle.css" rel="stylesheet">
<meta name = "viewport" content="width=device-width, initial-scale=1">
<link rel = "icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
main.ts is the file from where we start our project development. It starts with
importing the basic module which we need. Right now if you see angular/core,
angular/platform-browser-dynamic, app.module and environment is imported by
default during angular-cli installation and project setup.
platformBrowserDynamic().bootstrapModule(AppModule);
bootstrap: [AppComponent]
polyfill.ts
This is mainly used for backward compatibility.
styles.css
This is the style file required for the project.
test.ts
Here, the unit test cases for testing the project will be handled.
tsconfig.app.json
This is used during compilation, it has the config details that need to be used to run
the application.
tsconfig.spec.json
This helps maintain the details for testing.
typings.d.ts
It is used to manage the TypeScript definition.
Components
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
ng g component new-cmp
installing component
create src\app\new-cmp\new-cmp.component.css // CSS
create src\app\new-cmp\new-cmp.component.html // HTML
create src\app\new-cmp\new-cmp.component.spec.ts // unit testing
create src\app\new-cmp\new-cmp.component.ts // module, properties, etc
update src\app\app.module.ts // Updation of root app
In the app.component.html
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
<!--To include the design of the new components -->
<app-new-cmp></app-new-cmp>
<app-my-new-component></app-my-new-component>
</div>
Modules
Module in Angular refers to a place where you can group the components,
directives, pipes, and services, which are related to the application.
In case you are developing a website, the header, footer, left, center and the right
section become part of a module.
To define module, we can use the NgModule. When you create a new project using
the Angular –cli command, the ngmodule is created in the app.module.ts file by
default
To import NgModule
import { NgModule } from '@angular/core';
Data Binding
Curly braces are used for data binding. {{}} – this process is called as interpolation.
The variable in the app.component.html file is referred as {{title}} and the value of
title is initialized in the app.component.ts file and in app.component.html, the
value is displayed.
In the app.component.ts, declare the array deptt and assign values to it.
In app.component.ts
myClickFunction(event) {
alert("Button is clicked");
console.log(event);
}
changedeptt(event) {
console.log("Changed month from the Dropdown");
console.log(event);
}
Directives
Directives in Angular is a js class, which is declared as @directive. We have 3
directives in Angular. The directives are listed below −
Component Directives:
These form the main class having details of how the component should be
processed, instantiated and used at runtime.
Structural Directives
A structure directive basically deals with manipulating the DOM elements. Structural
directives have a * sign before the directive. For example, *ngIf and *ngFor.
Attribute Directives
Attribute directives deal with changing the look and behavior of the dom element.
Pipes
The | character is used to transform data.
It takes integers, strings, arrays, and date as input separated with | to be converted
in the format as required and display the same in the browser.
<b>{{title | uppercase}}</b><br/>
<b>{{title | lowercase}}</b>
Example
app.component.ts:
todaydate = new Date();
jsonval = {school:'Computing', deptt:'CSE', address:{course1:'B.E.', course2:'M.E.',
course3: ‘B.Sc’, course4:’PhD’}};
app.component.html
<div style = "width:100%;">
<div style = "width:40%;float:left;border:solid 1px black;">
<h1>Uppercase Pipe</h1>
<b>{{title | uppercase}}</b><br/>
<h1>Lowercase Pipe</h1>
<b>{{title | lowercase}}</b>
<h1>Currency Pipe</h1>
<b>{{6589.23 | currency:"USD"}}</b><br/>
<b>{{6589.23 | currency:"USD":true}}</b> //Boolean true is used to get the sign
of the currency.
<h1>Date pipe</h1>
<b>{{todaydate | date:'d/M/y'}}</b><br/>
<b>{{todaydate | date:'shortTime'}}</b>
<h1>Decimal Pipe</h1>
<b>{{ 454.78787814 | number: '3.4-4' }}</b> // 3 is for main integer, 4 -4 are for
integers to be displayed.
</div>
<div style = "width:40%;float:left;border:solid 1px black;">
<h1>Json Pipe</h1>
<b>{{ jsonval | json }}</b>
<h1>Percent Pipe</h1>
<b>{{00.54565 | percent}}</b>
<h1>Slice Pipe</h1>
<b>{{deptt | slice:2:6}}</b>
// here 2 and 6 refers to the start and the end index
</div>
</div>
Routing
Routing basically means navigating between pages. You have seen many sites with
links that direct you to a new page. This can be achieved using routing. Here the
pages that we are referring to will be in the form of components.
app.module.ts
import { RouterModule} from '@angular/router';
imports: [
BrowserModule,
RouterModule.forRoot([
{
path: 'new-cmp',
component: NewCmpComponent
}
])
],
new-cmp.component.ts
export class NewCmpComponent implements OnInit {
newcomponent = "Using Routing through Components";
constructor() { }
ngOnInit() {
}
}
new-cmp.component.html
<p>
New Component Successfully Created...
{{newcomponent}}
</p>
app.component.html
<a routerLink = "new-cmp">New component</a>
<router-outlet></router-outlet>
Forms:
• Template Driven Form
• Model Driven Form
With a template driven form, most of the work is done in the template; and with the
model driven form, most of the work is done in the component class.
To create Template driven form. To create a simple login form and add the email id,
password and submit the button in the form.
In app.module.ts
import { FormsModule } from '@angular/forms';
imports: [
BrowserModule,
FormsModule
],
In app.component.ts
export class AppComponent {
title = 'Forms using AngularJS 4.0';
onClickSubmit(data) {
alert("Entered Email id : " + data.emailid + data.passwd);
}
In app.component.html
<form #userlogin = "ngForm" (ngSubmit) = "onClickSubmit(userlogin.value)" >
Email Id: <input type = "text" name = "emailid" placeholder = "emailid" ngModel>
<br/><br/>
Password: <input type = "password" name = "passwd" placeholder = "passwd"
ngModel>
<br/><br/>
<input type = "submit" value = "Submit">
</form>
In app.component.ts
import { FormGroup, FormControl } from '@angular/forms';
In cmp-model-form.components.ts
import { FormGroup, FormControl } from '@angular/forms';
export class CmpModelFormComponent implements OnInit {
formdata;
emailid;
password;
constructor() { }
ngOnInit() {
this.formdata = new FormGroup({
emailid: new FormControl("[email protected]"),
passwd: new FormControl("abcd1234")
});
}
onClickSubmit(data) {
this.emailid = data.emailid;
this.password = data.passwd;
}
}
In cmp-model-form.component.html
<div>
<form [formGroup]="formdata" (ngSubmit) = "onClickSubmit(formdata.value)" >
<input type="text" class="fortextbox" name="emailid" placeholder="emailid"
formControlName="emailid">
<br/>
<input type="password" class="fortextbox" name="passwd"
placeholder="passwd" formControlName="passwd">
<br/>
<input type="submit" class="forsubmit" value="Log In">
</form>
</div>
<p>
Email entered is : {{emailid}}
<br/><br/>
Password is : {{password}}
</p>
Form Validation
Angular has built-in validators such as mandatory field, minlength, maxlength, and
pattern. These are to be accessed using the Validators module.
In cmp-validate-form.components.ts
<p>
Email entered is : {{emailid}}
</p>
ReactJS
Evolution Of React
React is a JavaScript library used to build the user interface for web
applications. React was initially developed and maintained by the folks at Facebook,
which was later used in their products (WhatsApp & Instagram). Now it is an open
source project with an active developer community. Popular websites like Netflix,
Airbnb, Yahoo!Mail, KhanAcademy, Dropbox and many more use React to build
their UI. Modern websites are built using MVC (model view controller) architecture.
React is the ‘V’ in the MVC which stands for view, whereas the architecture is
provided by Redux or Flux. React native is used to develop mobile apps, the
Facebook mobile app is built using React native.
React Features
• JSX − JSX is JavaScript syntax extension. It isn't necessary to use JSX in
React development, but it is recommended. JSX Allows us to include ‘HTML’
in the same file along with ‘JavaScript’ (HTML+JS=JSX). Each component in
React generates some HTML which is rendered by the DOM.
• ES6 (ES2015) - The sixth version of JavaScript is standardized by ECMA
(European Computer Manufacturers Association) International in 2015.
Hence the language is referred to as ECMAScript. ES6 is not completely
supported by all modern browsers.
• ES5(ES2009) - This is the fifth JavaScript version and is widely accepted by
all modern browsers, it is based on the 2009 ECMA specification standard.
Tools are used to convert ES6 to ES5 during runtime.
• Webpack - A module bundler which generates a build file joining all the
dependencies.
• Babel - This is the tool used to convert ES6 to ES5. This is done because not
all web browsers can render React (ES6+JSX) directly.
• Components − React is all about components. You need to think of
everything as a component. This will help you maintain the code when
working on larger scale projects.
• Unidirectional data flow and Flux − React implements one-way data flow
which makes it easy to reason about your app. Flux is a pattern that helps
keeping your data unidirectional.
• License − React is licensed under the Facebook Inc. Documentation is
licensed under CC BY 4.0.
React Advantages
• Uses virtual DOM which is a JavaScript object. This will improve apps
performance, since JavaScript virtual DOM is faster than the regular DOM.
• Can be used on client and server side as well as with other frameworks.
• Component and data patterns improve readability, which helps to maintain
larger apps.
React Limitations
• Covers only the view layer of the app, hence you still need to choose other
technologies to get a complete tooling set for development.
• Uses inline templating and JSX, which might seem awkward to some
developers.
Components
• The entire application can be modeled as a set of independent components.
Different components are used to serve different purposes. This enables us to
keep logic and views separate. React renders multiple components
simultaneously. Components can be either stateful or stateless.
• Before we start creating components, we need to include a few ‘import’
statements.
• In the first line, we have to instruct JavaScript to import the ‘react’ library from
the installed ‘npm’ module. This takes care of all the dependencies needed by
React.
Props
• “All the user needs to do is, change the parent component’s state, while the
changes are passed down to the child component through props.”
• Props is a shorthand for properties. React uses ‘props’ to pass attributes from
‘parent’ component to ‘child’ component.
• Props are the argument passed to the function or component which is
ultimately processed by React.
Example:
function Message(props) {
return <h1>Department of {props.deptt}, School of Computing</h1>;
}
function App() {
return (
<div>
<Message deptt="Computer Science and Engineering" />
<Message deptt="Information Technology" />
<Message deptt="Computer Science" />
</div>
);
}
ReactDOM.render(<App/>,document.getElementById('root'));
State
• State allows us to create components that are dynamic and interactive.
• State is private, it must not be manipulated from the outside.
• It is generally used with data that is bound to change.
• For Example, when we click a toggle button it changes from ‘inactive’ to
‘active’ state.
• State is used only when needed, make sure it is used in render() otherwise
don’t include it in the state. We do not use ‘state’ with static components.
• The state can only be set inside the constructor.
• Binding is needed explicitly, as by default the event is not bound to the
component.
handleClick() {
this.setState(prevState =>({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return(
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON': 'OFF'} );
}
State Lifecycle
• It is required to initialize resources to components according to their
requirements. This is called “mounting” in React.
• It is critical to clear these resources taken by the components when they are
destroyed.
• This is because performance can be managed and unused resources can be
destroyed. This is called “unmounting” in React.
• It is not essential to use state lifecycle methods, but use them if you wish to
take control of the complete resource allocations and retrieval process.
• State lifecycle methods component DidMount() and componentWillUnmount()
are used to allocate and release resources respectively.
Create an object called Timer ID and set an interval of 2 seconds. Now, this is the
time interval based on which the page is refreshed.
componentDidMount() {
this.timerID = setInterval( () => this.tick(),2000);
}
Here the interval is the timeframe after which the resources are cleared and the
component should be destroyed. Performing such manipulations on the dataset
using ‘state’ can be viewed as an optimal approach.
A timer is set to call tick() method once every two seconds. An object with current
Date is passed to set state. Each time React calls the render() method,
this.state.date value is different. React then displays the updated time on the
screen.
tick(){this.setState({date:new Date()});}
render() {
return (
<div>
<h2>The Time is {this.state.date.toLocaleTimeString()}.</h2>
</div>);
}
ReactDOM.render( <Time />, document.getElementById('root') );
}
Keys
• Keys in React provide identity to components.
• Keys are the means by which React identifies components uniquely.
• For individual components keys are not required as react takes care of key
assignment according to their rendering order.
• However, a strategy is required to differentiate between thousands of
elements in a list. It is required to assign the elements ‘keys’.
• To access the last component in a list using keys, the time required to
traverse the entire list sequentially is saved.
• Keys serve to keep track of which items have been manipulated.
• Keys should be given to the elements inside the array to give the elements a
stable identity.
Example:
• Create an array ‘Data’ with four items,
• Assign each item the index ‘i’ as the key.
• By defining the key as a property(‘Prop’)
• Use the JavaScript ‘map’ function to pass the key on each element of the
array and return the result to the ‘content’ component.
Software Requirements
I For Beginner
nodejs
https://github.com/facebook/create-react-app
II Detailed Requirements
npm init
npm install –g babel
npm install –g babel-cli
npm install webpack –save
npm install webpack-dev-server –save
npm install react –save
npm install react-dom –save
npm install babel-core
npm install babel-loader
npm install babel-preset-react
npm install babel-preset-es2015
npm install webpack-dev-server -g
npm install webpack-cli –D
Example 1:
npm install –g create-react-app
create-react-app first-react-app
cd first-react-app
npm start
In Browser, http://localhost:3000
Example 2:
index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<title>My First React App</title>
</head>
<body>
<div id = "app"></div>
<script src = "index.js"></script>
</body>
</html>
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
webpack.config.js
var config = {
entry: './main.js',
output: {
path:'/',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;
App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
Hello World!!!
</div>
);
}
}
export default App;
npm start
In browser, launch the app as localhost:8080
Example 2: /src/App.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import logo from './logo.svg';
import './App.css';
this.state = {
header: "Header from state...",
content: "Content from state..."
}
this.test = {
data: []
}
this.setTestHandler = this.setTestHandler.bind(this);
this.forceUpdateHandler = this.forceUpdateHandler.bind(this);
this.findDomNodeHandler = this.findDomNodeHandler.bind(this);
}
forceUpdateHandler() {
this.forceUpdate();
};
findDomNodeHandler() {
var myDiv = document.getElementById('myDiv');
ReactDOM.findDOMNode(myDiv).style.color = 'green';
}
setTestHandler() {
var item = "setTest..."
var myArray = this.test.data.slice();
myArray.push(item);
this.test.data=myArray;
this.setState({data: myArray})
};
render() {
var i=1;
var mystyle= {
fontSize: 100,
color: '#FF0000'
}
return (
<div className="App">
{//Single Line Comment...
}
{/* Multi line Comment */}
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<p> Welcome to ReactJS</p>
<h1>{1+1}</h1>
<h1>{i == 1 ? 'True!' : 'False'}</h1>
<h1 style={mystyle}>User defined Style</h1>
{/* Properties */}
<h1>{this.state.header}</h1>
<h2>{this.state.content}</h2>
{/* Properties with Validation */}
<h1> Hello, {this.props.name} </h1>
<h3>Array: {this.props.propArray}</h3>
<h3>Bool: {this.props.propBool ? "True..." : "False..."}</h3>
<h3>Func: {this.props.propFunc(3)}</h3>
<h3>Number: {this.props.propNumber}</h3>
<h3>String: {this.props.propString}</h3>
<button onClick = {this.setTestHandler}>SET STATE</button>
<h4>State Array: {this.test.data}</h4>
<button onClick = {this.forceUpdateHandler}>FORCE
UPDATE</button>
<h4>Random number: {Math.random()}</h4>
<button onClick = {this.findDomNodeHandler}>FIND DOM
NODE</button>
<div id = "myDiv">NODE</div>
</div>
);
}
}
App.propTypes = {
name: PropTypes.string,
propArray: PropTypes.array.isRequired,
propBool: PropTypes.bool.isRequired,
propFunc: PropTypes.func,
propNumber: PropTypes.number,
propString: PropTypes.string,
};
App.defaultProps = {
name: 'CSE',
propArray: [1, 2, 3, 4, 5],
propBool: true,
propFunc: function(e) {
return e
},
propNumber: 1,
propString: "String value..."
}
export default App;
Example
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
setTimeout(() => {
ReactDOM.unmountComponentAtNode(document.getElementById('root'));},
10000);
App.js
import React, { Component } from 'react';
import './App.css';
Example: App.js
import React, { Component } from 'react';
import './App.css';
Keys:
import React, { Component } from 'react';
import './App.css';
Router
Home.js
import React, { Component } from 'react';
class Home extends Component {
render() {
return (
<div>
<h2>Home</h2>
</div>
);
}
}
export default Home;
Login.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Login extends Component {
render() {
return (
<div>
<h2>Login</h2>
</div>
);
}
}
export default Login;
App.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-
dom';
import Home from './Home';
import Login from './Login';
import './App.css';
class App extends Component {
render() {
return (
<Router>
<div>
<h2>Welcome to React Router</h2>
<ul>
<li><Link to={'/'}>Home</Link></li>
<li><Link to={'/Login'}>Login</Link></li>
</ul>
<hr />
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/Login' component={Login} />
</Switch>
</div>
</Router>
</div>
);
}
}
export default App;