What is ReactJS?
=> It is a JavaScript library created by facebook..
=> It is used build front end application or user interfaces.
=> It allows to use usable component.
What is Component ?
=> Components are the building blocks of any React app.
Advantages of ReactJS
=> Reusable components
=> Open source
=> Efficient and Fast
=> Works in Browser
=> Large community
How React Works ?
=> React renders component to DOM and creates a virtual DOM to store components.
=> When we changes content of component, it will create virtual DOM and compare it to old virtual DOM and changes are rendered to DOM.
=> It is benefited by only updating the component whose content is changed and reloading the whole page.
=> It will only update the component which is modified.
Summary:-
=> It creates a virtual DOM and when we modify something, it will create another virtual DOM and compare it with older one.
=> According to the changes found in virtual DOM, it will modify component.
=> It doesn’t reload the page but only modifies component so It makes process faster.
Setup ReactJS project using CDN link
=> For making any react app, we need..
=> React package
=> React DOM package
=> we need react package to make component and to use render method we need react-Dom package.
=> we use babel to translate code which can be understood by browser.
What is NPM ?
- It is used to easily install and update Third-party packages.
What is Webpack ?
=> It is a static module bundler for modern javaScript application.
=> When webpack processes our application, it internally builds a dependency graph which maps every module which is needed by project and generates one or more bundles.
What is Babel ?
=> Babel is a toolchain that is used to convert ECMAScript 2015+ code into backward compatible version of JavaScript in current and older browsers or environment.
React.createElement(type, props, children)
=> It creates a React Element with the given arguments.
type: Type of HTML element or component.( example: h1, h2, p, button etc..)
props: The properties object.
Example: { style : { color : “blue” }} or className, event handlers etc.
children: anything pass between DOM element.
Ex:- React.createElement(‘div’, null, ‘Hello World’);
render() Method
=> It examines this.props and this.state.
=> It returns one of the following.
React element:
=> these are created via JSX.
Ex:-
<div /> and <App /> are react elements that instruct React to render a DOM node, or another user defined component.
Arrays and fragments:
=> It is used to return multiple elements from render.
Portals:
=> It is used to return children into a different DOM subtree.
String and numbers:
=> These are rendered as Text nodes in the DOM.
Booleans
and null:
=> It renders nothing. (Mostly exists to support return test && <Child/> pattern, where test is Boolean.
ReactDOM.render(element, DOMnode)
=> It takes a React element and render it to a DOM node.
=> The first argument is - component or element needs to render in the DOM.
=> second argument – where to render in DOM.
Ex:-
ReactDOM.render(
<App />, document.getElementById(“root”));
React App without using JSX and Babel
<div id=’root’></div>
<script>
class App extends React.Component{
render(){
return (React.createElement(‘div’, null, “Hello Word”));
}}
ReactDom.render(React.createElement(App, null), document.getElementById(“root”));
</script>
React app by using JSX and Babel
<div id=’root’></div>
<script>
class App extends React.Component{
render(){
return (
<div> Hello World </div>);
}}
ReactDOM.render(<App />, document.getElementById(‘root));
</script>
Create React App
- => Create React App sets up the tools we need to start our React project.
- => It installs latest version of react, react-DOM, react-script.
- => React, JSX, ES6, Typescript and Flow syntax support.
- => Auxoprefixed CSS.
- => Installs the dependencies needed to build project.
- => Zero setup and configuration required.
o Webpack:
=> It configures webpack to bundle our project.
Babel:
=> It transpile JSX into browser ready code.
Create React App
=> Create the initial project structure.
=> Development server
=> Built-in-testing –Jest testing framework
=> Create React app provides error message in browser.
Syntax:-
=> npx create-react-app <my-app>
- => npm start – to start development server
Directory Structure
- node_modules:
=> It contains all packages and dependencies installed.
-
Public:
=> favicon.ico – It’s a favicon of our website.
index.html – This file holds the HTML template of our app.
o manifest.json – manifest.json provides metadata used our when app is installed on user’s desktop or mobile.
src folder
=> App.css
– It’s a css file related to App.js but its global.
=> App.js
– It’s parent component of our react app.
=> App.test.js
– It is Test environment
=> index.css
– It’s a css file related to index.js but it is global
=> index.js
– It’s javascript entry point
=> logo.svg
– React logo file
=> serviceWorker.js
– It can help to access website offline.
=> .gitignore
– It is used to ignore git push.
=> package-lock.json
– It is version control package json file.
=> package.json
– all dependencies mentioned in file.
=> README.md
– It is readme file
Public Folder:
- => Webpack doesn’t read the public folder and not process
files inside it.
- => It will only read the files inside src folder.
- => To reference assets in the public folder, we need to use a special variable called PUBLIC_URL.
- => Only files inside the public folder will be accessible by %PUBLIC_URL% prefix.
Ex:-
<link rel=”shortcut icon” href=”%PUBLIC_URL%/favicon.ico
- => When we run, npm run build, create React app will substitute %PUBLIC_URL% with a correct absolute path so our project works even if we use client side routing or host it at non-root URL.
What is React Fragment ?
=> We can’t return multiple element’s using render method so for rendering multiple element, we use react fragment method.
=> Fragment is used to group a list of children without adding extra nodes to DOM.
Syntax:-
=> <React.Fragment></React.Fragment>
=> Shorter version - <></>
Ex:
<React.Fragment>
<h1>Hello</h1>
<h2>Sarita Borad</h2>
</React.Fragment>
2) Shorter version of above syntax
<>
<h1>Hello</h1>
<h2>Sarita Borad</h2>
</>
3)React Fragment using Id
Syntax:-
<React.Fragment key={id}></React.Fragment>
Ex:
<React.Fragment key=item.id>
<h1>{item.title}</h1>
<p>{item.description}</p>
</React.Fragment>
In Index.js file
- import ReactDOM from ‘react-dom’;
- import App from ‘./App’
ReactDOM.render(<App />, document.getElementById(“root”))
In App.js file
- import React, {Component} from ‘react’;
class App extends Component{
render(){
return (<React.Fragment>
<h1>Hello</h1>
<h2>Good Day Sarita Borad</h2>
</React.Fragment>);
}
}
export default App;
or
- import React, {Component, Fragment} from ‘react’;
class App extends Component{
render(){
return (<Fragment>
<h1>Hello</h1>
<h2>Good Day Sarita Borad</h2>
</ Fragment>);
}
}
export default App;
Function Component and Class Component
=> Components are the building blocks of any React App.
=> Component let us split the UI into independent, reusable pieces.
- => Components are like javascript functions.
=> They accept arbitrary inputs (called props) and return React elements describing what should appear on the screen.`=> Always start component name with Capital letter.
=> React treats components starting with lower case as DOM tags.
Ex:- <div> represents HTML div tag.
But <App /> represents a component
Function (functional) Component:-
=> It is a javascript function which accepts a single ‘props’ object argument with data and return React element.
Without props
Syntax:-
function func_name(){
return React Element;
}
Ex:-
function Student(){
return <h1>Hello Sarita</h1>
}
Or
const Student = () => {
return <h1>Hello Sarita</h1>
}
With props
Syntax:-
function func_name(props){
return React Element;
}
Ex:-
function Student(props){
return <h1>Hello Sarita</h1>
}
function Student(props){
return <h1>Hello {props.name}</h1>
}
Or
const Student = (props) => {
return <h1>Hello {props.name}</h1>
}
Class component
=> To make class component we need to extend React.Component.
=> class must implement render() function, which returns React Component to be rendered similar to return value of a functional component.
=> In class-based component, props are accessible via this.props.
Syntax:
class class_name extends Component{
render(){
return React Element
}
}
Ex:
class Student extends Component{
render(){
return (
<h1>hello sarita</h1>
)
}}
Class with props
class Student extends Component{
render(){
return <h1>Hello {this.props.name}</h1>
}
}
Rendering a Component
=> ReactDOM.render(<Student/>,
document.getElementById(‘root’));
=> ReactDOM.render(<Student name =’sarita’/>, document.getElementById(‘root’));
Ex:-
Function Student(props){
return <h1>Hello Sarita</h1>
}
ReactDOM.render(<Student name=’Sarita’/>, document.getElementById(‘root’));
=> When react finds element representing a user-defined component, it passes JSX attribute to this component as a single object. We call this object “props’.
=> Components can refer to other components in their output.
=> This let us use the same component abstraction for any level of detail.
Ex:-
Function Student(){
return <h1>Hello Sarita</h1>
}
function App(){
return (
<div>
<Student />
<Student />
<Student />
</div>
);}
ReactDOM.render(<App />, document.getElementById(‘root’));
When to Use Functional or Class Component ?
-
Use
functional components when..
=> Component which doesn’t have its own state or needs to access a life cycle hook.
=> We can’t use setState() in our component because Functional Components are plain JavaScript function.
- Use Class Component when..
=>
when we need state or need to access lifecycle hook because all life
cycle hooks are coming from the React Component which we extend from
class component.
- JavaScript JSON
=> JSON is a format for storing and transporting data.
=> JSON is often used when data is sent from a server to a web page.
What is JSON?
=> JSON stands for JavaScript Object Notation
=> JSON is a lightweight data interchange format
=> JSON is language independent *
=> JSON is "self-describing" and easy to understand
=> The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only.
=> Code for reading and generating JSON data can be written in any programming language.
JSON
Example
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
=> The JSON Format Evaluates to JavaScript Objects
=> The JSON format is syntactically identical to the code for creating JavaScript objects.
=> Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects.
JSON Syntax Rules
=> Data is in name/value pairs
=> Data is separated by commas
=> Curly braces hold objects
=> Square brackets hold arrays
JSON Data:
=> A Name and a Value
=> JSON data is written as name/value pairs, just like JavaScript object properties.
=> A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:
"firstName":"John"
=> JSON names require double quotes. JavaScript names do not.
JSON Objects
=> JSON objects are written inside curly braces.
=> Just like in JavaScript, objects can contain multiple name/value pairs:
{"firstName":"John", "lastName":"Doe"}
JSON Arrays
=> JSON arrays are written inside square brackets.
Just like in JavaScript, an array can contain objects:
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
=> Converting a JSON Text to a JavaScript Object
=> A common use of JSON is to read data from a web server, and display the data in a web page.
=> For simplicity, this can be demonstrated using a string as input.
First, create a JavaScript string containing JSON
syntax:
let text = '{ "employees" : [
{
"firstName":"John" , "lastName":"Doe"
},
{
"firstName":"Anna" , "lastName":"Smith"
},
{ "firstName":"Peter"
, "lastName":"Jones" } ]}';
=> Then,
use the JavaScript built-in function JSON.parse()
to
convert the string into a JavaScript object:
const obj = JSON.parse(text);
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName
+ " "
+ obj.employees[1].lastName;
</script>
Why JSON is Better Than XML ?
=> XML is much more difficult to parse than JSON.
JSON is parsed into a ready-to-use JavaScript object.
For AJAX applications, JSON is faster and easier than XML:
Using XML
Fetch an XML document
Use the XML DOM to loop through the document
Extract values and store in variables
Using JSON
Fetch a JSON string
JSON.Parse the JSON string
JSON.parse()
=> A common use of JSON is to exchange data to/from a web server.
=> When receiving data from a web server, the data is always a string.
=> Parse the data with JSON.parse()
,
and the data becomes a JavaScript object.
Example - Parsing JSON
=> Imagine we received this text from a web server:
'{"name":"John", "age":30, "city":"New York"}'
=> Use the JavaScript function JSON.parse()
to convert text into a JavaScript object:
const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
Array as JSON
=> When using the JSON.parse()
on a JSON derived from an array, the method will return a JavaScript array,
instead of a JavaScript object.
const text = '["Ford", "BMW", "Audi", "Fiat"]';
const myArr = JSON.parse(text);
Exceptions
Parsing Dates
=> Date objects are not allowed in JSON.
=> If you need to include a date, write it as a string.
=> You can convert it back into a date object later:
Or
=> you can use the second parameter, of the JSON.parse()
function, called reviver.
=> The reviver parameter is a function that checks each property, before returning the value.
=> Convert a string into a date, using the reviver function:
const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
const obj = JSON.parse(text, function (key, value) {
if (key == "birth") {
return new Date(value);
} else {
return value;
}
});
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;
Parsing Functions
=> Functions are not allowed in JSON.
=> If you need to include a function, write it as a string.
Convert a string into a function:
const text = '{"name":"John", "age":"function () {return 30;}", "city":"New York"}';
const obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age();
JSON.stringify()
=> When sending data to a web server, the data has to be a string.
=> Convert a JavaScript object into a string with JSON.stringify()
=> Stringify a JavaScript Object
Imagine we have this object in JavaScript:
const obj = {name: "John", age: 30, city: "New York"};
=> Use the JavaScript function JSON.stringify()
to convert it into a string.
const myJSON = JSON.stringify(obj);
The result will be a string following the JSON notation. myJSON
is now a string, and ready to be sent to a server:
Stringify a JavaScript Array
=> It is also possible to stringify JavaScript arrays:
Imagine we have this array in JavaScript:
const arr = ["John", "Peter", "Sally", "Jane"];
Use the JavaScript function JSON.stringify() to convert it into a string.
const myJSON = JSON.stringify(arr);
JavaScript XML(JSX):
- => JSX allows us to write HTML in React.
- => JSX makes it easier to write and add HTML in React.
- => JSX is a pre-processor step that adds XML syntax to JavaScript.
- => JSX produces React “element”.
- => It is possible to create element without JSX but JSX make react easier.
-