Unit-1 Introduction To React and ES6 OLD
Unit-1 Introduction To React and ES6 OLD
http://localhost:3000
npx is an NPM package runner which gets installed when
you install node
NOTE: You’ll need to have Node >= 14.0.0 and npm >= 5.6 on your machine. To create a project, run:
Installation or Setup
install the package globally using the command prompt
npm install -g create-react-app
once it is installed you can run the command create react app followed by the project name
Then run the generator in your chosen directory.
Npx create-react-app my-app
Navigate to the newly created directory and run the start script.
cd my-app/
npm start
Basic folder structure
Basic folder structure
package.JSON: contains the dependencies
the index.HTML is the only HTML file you are going to have in your application
Workflow
<div className="App"> }
React uses ES6, and you should be familiar with some of the new features like:
•Classes
•Arrow Functions
•Variables (let, const, var)
•Array Methods like .map()
•Destructuring
•Modules
•Ternary Operator
•Spread Attributes/operator
Spread Attributes/operator
● It's called spread attributes and its aim is to make function sum(x, y, z) { return x + y + z;}
the passing of props easier. const numbers = [1, 2, 3];
● Let us imagine that you have a component that console.log(sum(...numbers));
accepts N number of properties. Passing these // expected output:6
down can be tedious and unwieldy if the number
console.log(sum.apply(null, numbers));
grows.
// expected output: 6
● <Component x={} y={} z={} /> Thus instead you do
this, wrap them up in an object and use the
spread notation
● var props = { x: 1, y: 1, z:1 }; <Component
{...props} /> which will unpack it into the props
on your component, i.e., you "never" use {...
props} inside your render() function, only when
you pass the props down to another component.
Use your unpacked props as normal this.props.x.
Destructuring
<!DOCTYPE html>
<html>
● We may have an array or object that we are
working with, but we only need some of the
<body> items contained in these.
<script> ● Destructuring makes it easy to extract only
function calculate(a, b) { what is needed.
const add = a + b;
const subtract = a - b;
const multiply = a * b;
const divide = a / b;
</body>
</html>
Destructuring
//without destructuring //using destructuring
<!DOCTYPE html>
const vehicleOne = { <html>
brand: 'Ford',
<body>
model: 'Mustang',
type: 'car', <p id="demo"></p>
// allowed
let helloWorld = 'Welcome to the Road to learn React';
helloWorld = 'Bye Bye React';
However,
// allowed
const helloWorld = {
text: 'Welcome to the Road to learn React'
};
helloWorld.text = 'Bye Bye React';
return (
<div className="App">
<h2>{helloWorld.text}</h2>
</div>
);
Var vs let vs const
var a //declaration
a = 5 // initialization
let b //declaration
b = 10 //initialization
var c = 5 //declaration plus initialization in one step
let d = 5 //declaration plus initialization in one step
const a ; // SyntaxError: Missing initializer in const declaration
a = 5;
console.log(a);
const a = 5
console.log(a) //5
1: when we start our variable with var, let is called declaration. e.g: var a; or let a;
2: when we start our variable and assigning value it is declaration and initialization with value
3: const cannot be declared only, you need to initialize it with declaration
Var vs let vs const
import React, { Component } from 'react';
//capital first letter
// fun1(true);
class Let_var extends Component { return (
render() {
var helloWorld = 'Welcome to React'; <div
// const helloWorld = 'Welcome to the
Road to learn React';
className="App">
// helloWorld = 'Bye Bye React';
// let helloWorld = 'Welcome to the
Road to learn React';
<h2>{helloWorld}</h2>
// helloWorld = 'Bye Bye React'; </div>
// function fun1(a)
// { );
//
//
let helloWorld="ok global";
var hello = 'Welcome';
}
// if(a) }
// {
// let helloWorld = 'Welcome
to the Road to learn React';
//
to React';
var helloWorld1 = 'Welcome
export default Let_var;
// }
// console.log(helloWorld);
// console.log(hello);
// }
Var vs let vs const
1: var and let can change their value and const cannot change its
value
2: var can be accessible anywhere in function but let and const can
only be accessible inside the block where they are declared.
ReactDOM(index.js)
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
//it can also pass simple JSX.
{/* <h1>hello</h1> */}
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
ReactDOM.render(
<React.StrictMode>
ReactDOM
<App />
//it can also pass simple JSX.
{/* <h1>hello</h1> */}
</React.StrictMode>,
document.getElementById('root')
);
The second argument specifies the place where the React application hooks into your
HTML. It expects an element with an id='root', found in the public/index.html file.
document.getElementById('root')
);
Map function(in App.js) class App extends Component {
render() {
import React, { Component } from 'react'; return (
import './App.css';
const list = [ <div className="App">
{ {list.map(function(item) {
title: 'React', return <div>{item.title}</div>;
url: 'https://reactjs.org/', })}
author: 'Jordan Walke', </div>
num_comments: 3,
points: 4, );
objectID: 0, }
}, }
{ export default App;
title: 'Redux',
url: 'https://redux.js.org/',
author: 'Dan Abramov, Andrew Clark',
num_comments: 2,
points: 5,
objectID: 1,
},
];
Map function
const Array = [2, 3, 4, 5, 35]
map() creates a new array from
calling a function for every array const Array = Array.map(Item => {
element. return Item * 2
// allowed
<body>
<script>
class Car {
constructor(name) {
this.brand = name;
}
}
document.write(mycar.brand);
</script>
</body>
</html>
Es6 Promise
Promises used in JavaScript for asynchronous programming. For asynchronous programming, JavaScript used
callbacks but there is a problem using the callback which is callback hell or Pyramid of Doom. Using the ES6
Promise will simply avoid all the problems associated with the callback.
Es6 Promise
A Promise is always in one of the following states:
f1(function(x){
● fulfilled: Action related to the promise succeeded.
● rejected: Action related to the promise failed.
f2(x, function(y){ ● pending: Promise is still pending i.e not fulfilled or
rejected yet.
f3(y, function(z){ ● settled: Promise has fulfilled or rejected
...
.then(): Invoked when a promise is kept or broken. It can be
}); chained to handle the fulfillment or rejection of a promise
});
.catch() can be used for handling the errors(if any). It takes only one
function as a parameter which is used to handle the errors (if any)
});
Es6 Promise
})
Callback
//synchronous callback //asychronous callback uses timer
function show(){ function display(){
console.log("show"); setTimeout(function show(){
} console.log("show function
function display(callback){ calling");
callback(); }, 5000);
} console.log("display function
display(show); calling");
}
display();
//callback hell issue
addition(5,function(addres,err){
Callback
if(!err){
subtraction(addres,function(subres,err){
if(!err){
multiplication(subres,function(mulres,er
//asychronous anonymous callback r){
function display(callback){ if(!err){
console.log(mulres);
console.log("display function
}
calling"); });
callback(); }
});
}
}
display(function(){ });
console.log("show function
function addition (val,callback){
calling");
return callback(val+5,false);
}); }
function subtraction (val,callback){
return callback(val-3,false);
}
function multiplication (val,callback){
return callback(val*5,false);
}
Es6 Promise
var promise=new Promise(function(resolve,reject){
resolve(5);
// reject(5);
})
promise.then(addition).
then(subtraction).
then(multiplication).
then(function(ans){
console.log(ans);
}).catch(function(err){
console.log(err);
});
}
function errorHandler(err) {
else
reject('NOT_Postive_Number_Passed')
console.log('Handling error', err)
}) }
add_positivenos_async(10, 20) }
The export keyword can be used to export components in a module. Exports in a module can be classified as follows −
● Named Exports
● Default Exports
● Named Exports: import the component with the exact same name
Named exports are distinguished by their names.
/using multiple export keyword
export component1
export component2
export componentN
Or
export {component1,component2,....,componentN}
ES6 Modules
● Default Exports
Modules that need to export only a single value can use default exports. There can be only one default export
per module.
import the component with any name
Syntax
export default component_name
ES6 Modules file2.js
import { firstname, lastname } from './file1.js';
file1.js console.log(firstname);
// output: Jordan
const firstname = ‘Jordan';
OR
const lastname = ‘Walke'; file2.js
import * as person from './file1.js';
export { firstname, lastname };
console.log(person.firstname);
// output: Jordan
OR
file2.js
import { firstname as username } from './file1.js';
console.log(username);
// output: Jordan
ES6 Modules
file1.js
There is also the default statement, which can be const r = {
used for a few cases: firstname: ‘Jordan ',
• to export and import a single functionality lastname: ‘Walke ',
};
• to highlight the main functionality of the export default r;
exported API of a module
file2.js
You have to leave out the curly braces to import
import developer from './file1.js';
the default export.
console.log(developer);
The import name can differ from the exported // output: { firstname: ‘Jordan ', lastname: ‘Walke ' }
default name
ES6 Modules
file1.js
file2.js
const firstname = 'Jordan'; import developer, { firstname, lastname }
const lastname = ‘Walke',; from './file1.js';
const person = {
console.log(developer);
firstname,
};
Note: "Props" are simply the attributes used on a JSX node (e.g. <SomeComponent
someProp="some prop's value" />),
Functional component
a functional component is a JavaScript App.js(This is not index.js)
function that accepts an input of properties import Greet from './components/Greet'
and returns HTML that describes the UI import MyComponent from './components/Greet'
...
Greet.js ...
function App() {
import React from 'react' return (
function Greet(){ <div className="App">
return <h1>hello react</h1> {/* using functional component */}
<Greet></Greet>
} {/* using different name in import */}
// export const Greet = () => <MyComponent></MyComponent>
</div>
//<h1> hello react!</h1> );
export default Greet }
export default App;
Functional Component
Use snippet “rsf’ to create default functional component
Class Component
import React, {Component} from 'react'
//class component
class Welcome extends Component{
render()
{
return <h1>hello react!</h1>
}
}
export default Welcome
A functional component is just a plain A class component requires you to extend from React.
JavaScript function that accepts props as an Component and create a render function which returns a
argument and returns a React element. React element.
Constructors are not used . Constructor are used as it needs to store state.
Handler function in JSX
Handler function in JSX
it has to be a function that is passed to the <button onClick={() => this.onDismiss(item.objectID)}
event handler. type="button">
Dismiss
</button>
return ( <h2>
<div> {names[2]}
</h2>
{ </div>
nameList }
);
// names.map(x=><h2>{x}</h2>)
} export default NameList;
Lists
import React from 'react'; <h2>
function NameList(props) { {names[0]}
</h2>
const names=['one','two','three'];
const nameList = names.map((x, index) => ( <h2>
{names[1]}
<h2 key={index}> </h2>
{index} <h2>
{x} {names[2]}
</h2> </h2>
</div>
)); );
// when list has no unique key, list is static you }
● Single page applications (SPA) have become increasingly popular in recent years, as frameworks
like Angular, Ember, and Backbone allow JavaScript developers to build modern web
applications using techniques beyond vanilla JavaScript and jQuery. The three mentioned are
among the first.
● SPAs, each coming into its own between 2010 and 2011, but there are many more options for
single- page development. The first generation of SPA frameworks arrived at the enterprise
level, so their frameworks are more rigid. React, on the other hand, remains an innovative library
that has been adopted by many technological leaders like Airbnb, Netflix, and Facebook.
Single page applications
Single page applications
Single page applications
Pros of a Single-page Application:
● Performance. All resources are loaded during one session, and then, when interacting with the page, only the
necessary data is changed. This approach significantly increases web app performance.
● Improved user experience. Such apps provide users with a more understandable linear experience. Moreover,
the use of AJAX and JavaScript frameworks, as well as the fact that there is only one web page, allows building a
more flexible and responsive interface.
● Data caching. After the first request to the server, all the necessary local data is stored in the cache, and that
provides users with the possibility to work in an offline mode (for example, GoogleDocs offline mode).
● Development speed. All things equal, you will have to develop and test fewer app elements and will be able to
reuse part of the code.
● Ease of debugging. An SPA is most often developed based on popular frameworks (React, Vue.js, AngularJS)
that offer their own debugging tools based on Google Chrome, for example, Vue.js devtools.
Multipage applications
Multipage applications
In the case of a multi-page app, the entire web page content is refreshed, which is
also true about all the pages requested by the user.
Multipage applications
Pros of a Multi-page Application:
SEO optimization is possible. The app has multiple pages, and each of them can be
optimized for a specific group of requests to get free organic traffic from Google.
Ease of scaling. This architecture type allows creating as many new pages for each
product or service as you like and implementing any changes in them.
Analytic capabilities. Web analytics tools like Google Analytics can be easily
integrated into this type of project and allow tracking each business page’s performance.
Navigation Pages
import {Route,Routes} from 'react-router-dom'; import React from 'react’;
import Aboutus from './components/aboutus';
import { NavLink } from 'react-router-dom';
import Contactus from './components/contactus';
import User from './components/User';
import Menu from './components/Menu'; function Menu(props) {
function App() {
return (
return (
<div className="App"> <div>
<NavLink to='/' >Aboutus</NavLink>
<Menu></Menu> <NavLink to='/contact'>Contactus</NavLink>
<Routes>
<Route exact path="/"
<NavLink to='/user/abc'>User</NavLink>
element={<Aboutus/>}></Route> </div>
<Route path='/contact' );
element={<Contactus/>}></Route>
}
<Route path='/user/:name'
element={<User/>}></Route>
{/* //we can have error page for any random path */} export default Menu;
</Routes>
//install react-router-dom using npm
</div>
);
}
export default App;
Navigation Pages
import React from 'react'; import React from 'react';
import {useParams} from 'react-router-dom';
function Aboutus() { function User() {
return ( const {name}=useParams();
<div> return (
<h1>Aboutus</h1> <div>
</div> <h1>hello{name}</h1>
); </div>
} );
}
export default Aboutus;
export default User;