This blog tell user about daily facing problem in technology field, about programming language projects,what is and how to solve the problem and about programming language.
Tuesday, July 14, 2020
NINA + SING = AGAIN ? assign each alphabet with a number such that addition becomes true?
History of Artificial Intelligence?
History of Artificial Intelligence.
· 1950: Arthur Samuel developed a checkers-playing computer program.
· 1955: The first artificial intelligence computer program.
· 1958: developed Lisp, the most popular programming language for AI.
· 1959: “machine learning ” tern coined.
· 1964: an early ai program written in Lisp that solved algebraic word problems.
· 1965: ELIZA, an interactive chat-based computer program.
· 1995: ALICE was developed
· 1997: a chess-playing computer defeated Gary Kasparov
· 1999: Sony introduces AIBO.
· 2006: “machine reading” coined as an unsupervised autonomous understanding of the text.
· 2011: Apple released Siri, a virtual assistant on IOS.
· 2014: Microsoft released Cortona, Amazon Alexa
· 2016: Humanoid robot called Sophia is created.
· 2017: Facebook AI research lab trains two chatbots to talk among themselves.
· 2018: Samsung introduced Bixby
Importance of Artificial Intelligence?
Importance of Artificial Intelligence.
1. The smart device made with artificial intelligence can be available 24/7 hour.
2. Artificial intelligence can be used in digital assistance.
3. It handles the repetitive job better than a human can.
4. Artificial intelligence reduces errors.
5. Can be used to detect pattern better than human.
6. Used in sentiment analysis of the given text. It says either the given text is positive or negative
7. help in classification of data
List the AI applications every day you see?
List the AI applications every day you see.
- Google AI-powered Predictions Ridesharing apps like Uber and Lyft
- Commercial Flights Use an AI Autopilot
- Email-spam filters
- Smart email categorization
- Mobile check deposits
- Fraud Prevention
- Social networking, Facebook, Pinterest, Instagram,
Snapchat,
- Online shopping, search, recommendations, Fraud
Protection, Netflix, youtube
- Mobile use, voice to text, smart personal
assistance
- Opening your phone with face id.
Explain the possible AI applications in the following fields:
Possible application of AI?
- Agriculture:
It is mainly classified into three major categories:
1.
Agriculture
Robots – Companies are developing and programming robots to handle essential
agricultural tasks such as harvesting crops at a higher volume and faster pace
than human laborers.
2.
Crop
and Soil Monitoring –Companies are leveraging computer vision and
deep-learning algorithms to process data captured by drones and/or
software-based technology to monitor crop and soil health.
3.
Predictive
Analytics – Machine learning models are being developed to track and
predict various environmental impacts on crop yield such as weather changes.
- Tourism
The chatbot can be used
as a guide for tourists. Chatbots are ideal for customer-centric businesses. The chatbot can serve 24/7 frontend customer care techniques. Many question responses
can be automated using chatbots. Some flights are using mobile applications and
chatbots for updating their clients on the flight. It also answers questions
like what is the fun thing to do in London this weekend. Many brands are using
AI for customer services. Recommendation system for recommending the user about
the places around. AI can be used in weather prediction.
- Herbal Industry Automation
AI helps to mine
traditional medicine data. In short, AI helps to digitalize ancient medicine
books and clinical data. AI robots can be used to develop medicine in a large
scale.
- Stock Market
Ai can be used in time
forecasting of the stoke market. It can be used to interpret many stoke price data.
- Machine Translation
Ai is used in machine
translation, it understands the one language and using different AI algorithms AI the model can generate the same phrase into another language.
- Face Detection
There
are many algorithms that can detect the face of living being using AI approaches.
Some
are Feature-based, appearance-based, knowledge-based, template matching.
- Product Recommendation
Based
on the various parameter AI model can predict which item is best fit for which
customer at which time. The recommendation system predicts the product about which a person
is interested in.
- Image/Video Guided Surgery
This kind of surgery
uses different visualization tools to visualize the internal structure of the human
body parts. The automated overlay of the three-dimension reconstructions of
internal anatomy on top of live video views of the patient.
- Speech Recognition
Speech recognition is
a technology that can recognize spoken words, which can then be converted to
text. This involves various AI algorithms
to understand Speech.
- Universe Exploration
AI algorithms may result in the conclusion that helps
to explore the universe more effectively than human manual tasks. Recently, NASA
and Google in making the discovery of two obscure planets. One is a minuscule
sized planet in Kepler-90, now called Kepler-90i which is the super earth-sized
rocky planet.
Saturday, April 4, 2020
Tensor flow model that convert temperature in Celsius to Fahrenheit .
Celsius to Fahrenheit convertor
steps involved are:
1) Importing necessary dependencies:
2) Set up training data:
solar system animation in 3D in c language using openGL
Solar system animation in 3D
Tool used:
//necessary headerfile | |
#include <stdio.h> | |
#include <string.h> | |
#include <math.h> | |
#include <time.h> | |
#include "GL/glut.h" | |
#include "b.h" | |
// necessary variable declaration and initialization | |
bool one = false; | |
static float rotx = 0.0; | |
static float worldX = 15.0; | |
static float worldY = 0.0; | |
static float scaleFactor = 0.6; | |
static bool animate = false; | |
static float first = 1; | |
static float second = 1; | |
point stars[500]; | |
int globalW, globalH; | |
float speed = 0.5; | |
// for text display | |
void keimeno(const char *str, float size){ | |
glPushMatrix(); | |
glScalef(size, size, size); | |
for(int i = 0; i < strlen(str); i++) | |
glutStrokeCharacter(GLUT_STROKE_ROMAN, str[i]); | |
glPopMatrix(); | |
} | |
void Render(){ | |
//CLEARS FRAME BUFFER ie COLOR BUFFER& DEPTH BUFFER (1.0) | |
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); | |
glMatrixMode(GL_MODELVIEW); | |
glLoadIdentity(); | |
glTranslatef(0, 0, -500); | |
if (!animate) { | |
glPushMatrix(); | |
glDisable(GL_LIGHTING); | |
glDisable(GL_LIGHT0); | |
glColor3f(1, 1, 1); | |
glTranslatef(-8, 250, 0.0); | |
keimeno("Paused", 0.1f); | |
glPopMatrix(); | |
} | |
glEnable(GL_LIGHTING); | |
glEnable(GL_LIGHT0); | |
GLUquadricObj *quadric; | |
quadric = gluNewQuadric(); | |
gluQuadricDrawStyle(quadric, GLU_FILL); | |
gluDeleteQuadric(quadric); | |
glScalef(scaleFactor, scaleFactor, scaleFactor); | |
glRotatef(worldX, 1, 0, 0); | |
glRotatef(worldY, 0, 1, 0); | |
glDisable(GL_LIGHTING); | |
glPushMatrix(); | |
glColor3f(0.8, 0.498039, 0.196078); | |
gluSphere(quadric, 15, 36, 18); | |
glColor3f(1, 1, 0); | |
glEnable(GL_BLEND); | |
glBlendFunc(first, second); | |
gluSphere(quadric, 35, 36, 18); | |
glDisable(GL_BLEND); | |
glPopMatrix(); | |
glEnable(GL_LIGHTING); | |
GLfloat light_position[] = { 0.0, 0.0, 0.0,1 }; | |
glLightfv(GL_LIGHT0, GL_POSITION, light_position); | |
GLfloat light_diff[] = { 1.0, 1.0, 1.0, 1.0 }; | |
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diff); | |
GLfloat light_amb[] = { 0.0, 0.0, 0.0, 1.0 }; | |
glLightfv(GL_LIGHT0, GL_AMBIENT, light_amb); | |
glPushMatrix(); //1 planet | |
glRotatef(rotx*speed *1.9, 0, 1, 0); | |
glTranslatef(40, 0, -100.0); | |
glRotatef(rotx, 1, 0, 0); | |
glColor3f(1, 0.1, 0.6); | |
gluSphere(quadric, 17, 36, 18); | |
glPopMatrix(); | |
glPushMatrix();// 2 planet | |
glRotatef(rotx*speed * 1.8, 0, 1, 0); | |
glTranslatef(-200, 0.0, -150); | |
glRotatef(rotx, 0, 0, 1); | |
glColor3f(1, 0.1, 0.29); | |
gluSphere(quadric, 10, 16, 18); | |
glPopMatrix(); | |
glPushMatrix();// 3 planet | |
glRotatef(rotx* speed *1.7, 0, 1, 0); | |
glTranslatef(-60, 0, -200.0); | |
glRotatef(rotx, 1, 0, 0); | |
glColor3f(1, 0, 0); | |
gluSphere(quadric, 17, 36, 18); | |
glPopMatrix(); | |
glPushMatrix();// 4 planet | |
glRotatef(rotx*speed * 1.6, 0, 1, 0); | |
glTranslatef(20, 0, -250.0); | |
glRotatef(rotx, 1, 0, 0); | |
glColor3f(0.1, 0.6, 0.9); | |
gluSphere(quadric, 17, 36, 18); | |
glPopMatrix(); | |
glPushMatrix();// 5 planet | |
glRotatef(rotx *speed * 1.4, 0, 1, 0); | |
glTranslatef(-30, 0, -300.0); | |
glRotatef(rotx, 1, 0, 0); | |
glColor3f(1, 0.7, 0.3); | |
gluSphere(quadric, 13, 36, 8); | |
glPopMatrix(); | |
glPushMatrix();// 6 planet | |
glRotatef(rotx *speed * 1.3, 0, 1, 0); | |
glTranslatef(20, 0, -350.0); | |
glRotatef(rotx, 1, 0, 0); | |
glColor3f(0.5, 0, 0.5); | |
gluSphere(quadric, 17, 36, 18); | |
glPopMatrix(); | |
glPushMatrix();// 7 planet | |
glRotatef(rotx *speed * 1.5, 0, 1, 0); | |
glTranslatef(-30, 0, -400.0); | |
glRotatef(rotx, 1, 0, 0); | |
glColor3f(0.3, 0.8, 0); | |
gluSphere(quadric, 13, 36, 8); | |
glPopMatrix(); | |
glPushMatrix();// 8 planet | |
glRotatef(rotx *speed *1.2, 0, 1, 0); | |
glTranslatef(-30, 0, -450.0); | |
glRotatef(rotx, 1, 0, 0); | |
glColor3f(0.5, 0.5, 0.5); | |
gluSphere(quadric, 13, 36, 8); | |
glPopMatrix(); | |
DrawStars(); | |
glutSwapBuffers(); // All drawing commands applied to the | |
// hidden buffer, so now, bring forward | |
// the hidden buffer and hide the visible one | |
} | |
//----------------------------------------------------------- | |
void Resize(int w, int h) | |
{ | |
// define the visible area of the window ( in pixels ) | |
if (h == 0) h = 1; | |
glViewport(0, 0, w, h); | |
globalH = h; | |
globalW = w; | |
// Setup viewing volume | |
glMatrixMode(GL_PROJECTION); | |
glLoadIdentity(); | |
gluPerspective(60.0, (float)w / (float)h, 1.0, 1000.0); | |
} | |
void Idle() | |
{ | |
if (animate) | |
rotx += 1.1; | |
glutPostRedisplay(); | |
} | |
void Keyboard(unsigned char key, int x, int y) | |
{ | |
switch (key) | |
{ | |
case 'q': exit(0); | |
break; | |
case 'w': if (animate) worldX -= 1.0f; | |
break; | |
case 's': if (animate) worldX += 1.0f; | |
break; | |
case 'a': if (animate) worldY -= 1.0f; | |
break; | |
case 'd': if (animate) worldY += 1.0f; | |
break; | |
case ' ': animate = !animate; | |
break; | |
default: break; | |
} | |
glutPostRedisplay(); | |
} | |
void Setup() // TOUCH IT !! | |
{ | |
//get random cordinates for the stars | |
for (int i = 0; i < 500; i++) | |
RandomCoordinates(&stars[i]); | |
srand(time(0)); | |
//Parameter handling | |
glShadeModel(GL_SMOOTH); | |
glEnable(GL_DEPTH_TEST); | |
// polygon rendering mode | |
glEnable(GL_COLOR_MATERIAL); | |
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE); | |
// Black background | |
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); | |
} | |
void RandomCoordinates(point *star) | |
{ | |
int lowest = -1000, highest = 1000; | |
int range = (highest - lowest) + 1; | |
star->x = lowest + int(range*rand() / (RAND_MAX + 1.0)); | |
star->y = lowest + int(range*rand() / (RAND_MAX + 1.0)); | |
star->z = lowest + int(range*rand() / (RAND_MAX + 1.0)); | |
} | |
void DrawStars() | |
{ | |
GLUquadricObj *quadric; | |
quadric = gluNewQuadric(); | |
gluQuadricDrawStyle(quadric, GLU_FILL); | |
gluDeleteQuadric(quadric); | |
for (int i = 0; i < 500; i++) { | |
glPushMatrix(); | |
glTranslatef(stars[i].x, stars[i].y, stars[i].z); | |
glColor3f(1, 1, 1); | |
gluSphere(quadric, 1, 36, 18); | |
glPopMatrix(); | |
} | |
} |
Now we made custom header file named "b.h", and "b.cpp" file for defining header file function.
the source code for these file is also given as:
b.cpp source code:
#include <math.h> | |
#include "GL/glut.h" | |
#include <stdio.h> | |
#include <string.h> | |
#include "b.h" | |
// Header file for our OpenGL functions | |
int main(int argc, char* argv[]) | |
{ | |
// initialize GLUT library state | |
glutInit(&argc, argv); | |
glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE); | |
// Define the main window size and initial position | |
glutInitWindowSize(800, 800); | |
glutInitWindowPosition(50, 50); | |
// Create and label the main window | |
glutCreateWindow("Solar system"); | |
// Configure various properties of the OpenGL rendering context | |
Setup(); | |
// Callbacks for the GL and GLUT events: | |
// The rendering function | |
glutDisplayFunc(Render); | |
glutReshapeFunc(Resize); | |
glutIdleFunc(Idle); | |
glutKeyboardFunc(Keyboard); | |
//Enter main event handling loop | |
glutMainLoop(); | |
return 0; | |
} |
b.h source code:
struct point{ | |
float x; | |
float y; | |
float z; | |
}; | |
struct face { | |
int vtx[3]; | |
}; | |
extern int globalW, globalH; | |
//-------- Functions -------------------------------- | |
void Render(); | |
// The function responsible for drawing everything in the | |
// OpenGL context associated to a window. | |
void Resize(int w, int h); | |
// Handle the window size changes and define the world coordinate | |
// system and projection type | |
void Setup(); | |
// Set up the OpenGL state machine and create a light source | |
void Idle(); | |
void Keyboard(unsigned char key, int x, int y); | |
//functin for handling mouse whell event | |
void RandomCoordinates(point*); | |
void DrawStars(); | |
Wednesday, March 25, 2020
How to start with React-native application development?
About react native
1)What is React Native ?
->The java script library for building user interface is called React.
->Typically used for web development.
->It is a collection of special react components.
->Componenet compiled to Native widgets.
->Native platform APIs exposed to javascript.
->Connect javascript and native platform code.
2)react-native eg:
const App = props =>{return(
<View>
<Text>Hay bot</Text>
</View>
)
}
3)Create a new react native app
a)expo cli/tool(using this approach for this tutorial)
->third party service
->free
->managed app development workflow
->lots of convenience and utility features: simplifies development
b)react native cli
->managed by reactnative team
->bare bone development
->almost no convenience or utility feature
->full flaxibility: integrate with any native code
4.1)how expo works?
->goto expo.io
->install Node.js in your PC if not
->get the command line tool(eg:Anaconda powershell prompt)
npm install expo-cli --global
->Create your first project(navigate to the project directory folder)
expo init my-new-project
cd my-new-project
expo start
->use expo-client app in android mobile and scan qr code yields to app lunch which your going to building.
->this should give up and running output app.
->open the app folder in any text editor to further code.
4.2)how react native cli work?
(in one cmd)
->npm install -g react-native-cli
->npm install -g yarn
->react-native init myapp
->cd myapp
->react-native start
(in another cmd and goto myapp folder)
->react-native run-android
a)reactnatibe basics
->core components
i)built into react native
->"translation" to Native UI widgets provided by React Native
->eg:<View>
<Text>
<Button>/<Touchable...>
<TextInput>
<Image>
ii)Your UIs/Custom Components
->Composed of these "Core" Components and other build-in Components
->eg:const MyTitle = props=>{
return(
<View>
<Text>{props.title}</Text>
</View>
);
}
iii)styling
->inline style
->styleSheet objects(prefered)
->written in javascript
->Based on CSS syntax, influenced by CSS
<===============lets build an simple app ======================>
1)initially app.js code :
import React from 'react';
import { StyleSheet, Text, View} from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text>hi dude</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
2)After making app, app.js code:
import React, {useState} from 'react';
import { StyleSheet, Text, View, Button, TextInput} from 'react-native';
export default function App() {
const [enteredGoal, setEnteredGoal] = useState(' ');
const [courseGoals, setCourseGoals] = useState([]);
const goalInputHandler = (enteredText) => {
setEnteredGoal(enteredText);
};
const addGoalHandler= ()=>{
setCourseGoals(currentGoals =>[...currentGoals, enteredGoal]);
console.log(enteredGoal);
};
return (
<View style={styles.mainView}>
<View style={styles.inputContainer}>
<TextInput
placeholder={"Goal to achive"}
placeholderTextColor ={"green"}
style={styles.inputField}
onChangeText = {goalInputHandler}
/>
<Button
title={"Add me!"}
color={"coral"}
onPress={addGoalHandler}
/>
</View>
<View style={styles.showdataview}>
{courseGoals.map((goal) => <Text>{goal}</Text>)}
</View>
</View>
);
}
const styles = StyleSheet.create({
mainView:{
paddingTop:30,
padding:5,
},
inputContainer:{
flexDirection:"row",
justifyContent:"space-evenly",
},
inputField:{
backgroundColor:"lime",
paddingStart:20,
width:"75%",
borderColor:"cornflowerblue",
borderWidth: 2,
},
showdataview:{
backgroundColor:"pink",
height: "100%",
borderColor: "black",
borderWidth:2,
},
});
Brief documentation of React ?
About react
1)Introduction
->It is a javaScript library for building user interfaces.
->It is used to build single page application.
->Allows us to create reusable UI components.
->It is created by facebook.
->It is tool for building UI components.
2)How does react works?
->It creates a VIRTUAL DOM in memory.
->It does necessary manipulation in memory before making change in browser DOM.
->It only changes what needs to be changed.
3)React Components
->components are independent and reusable bitd of code.
->components come in two type.
a)Class component
->components name start with capital letter.
->Include the "extends React.Component" statement.
->Above statement create an inheritance to React.Component.
->Give your component excess to React.
->Requires a render() method, this method returns HTML.
->eg:class Car extends React.Component {
render(){
return <h1>I am class components </h1>;
}
}
//display the Car component in the "root" element
ReactDom.render(<Car/>, document.getElementById('root'));
b)function component
->similer to class component.
->Does not have render() method.
->Does not support inheritance.
->class component is more preferred.
->eg:function Car(){
return <h1>I am function components </h1>;
}
//display the Car component in the "root" element
ReactDom.render(<Car/>, document.getElementById('root'));
4)Component constructor
->To initiate the component properties called state.
->used in class component.
->To support the inheritance of the parent component "super()" method
is called in constructor function.
->"super()" method executes the parent components constructor function.
->class components have access to all the function of parent component
"React.Component".
->eg:class Car extends React.Component{
constructor(){
super();
this.state = {name: "Ford"};
}
render(){
return <h2>I am class component with constructor:{this.state.name}</h2>
}
}
5)Props
->Way of handling component properties.
->eg:class Car extends React.Component{
render(){
return <h2>I am a {this.props.name} car </h2>;
}
}
ReactDom.render(<Car name={"Ford"}>,document.getElementById('root'));
6)Components in Components
->Can refer to components inside other components.
->eg:class Car extends React.Component{
render(){
return (
<h2>I am a Car ! </h2>
);
}
}
class Garage extends React.Component{
render(){
return(
<div>
<h1>Who lives in my Garage? </h1>
<Car/>
</div>
);
}
}
ReactDOM.render(<Garage />, document.getElementById('root'));
7)Components in files
->create a new file with a .js file extension and put the code inside it.
->eg://code of a.js file
import React from 'react';
import ReactDOM from 'react-dom';
class Car extends React.Component {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}
export default Car;
//code of app.js file
import React from 'react';
import ReactDOM from 'react-dom';
import Car from './App.js';
ReactDOM.render(<Car />, document.getElementById('root'));
8)React Lifecycle
->Each component in react has a lifecycle.
->The three phases are:
a)Mounting
->process of putting element into the DOM.
->react has four build-in methods that gets called,
in order, when mounting a component.
i)constructor()
->called by react every time when you make a component
->eg:class Header extends React.Component{
constructor(props){
super(props);
this.state = {favoritecolor : "pink"};
}
render(){
return(
<h1>My favorite color is {this.state.favoritecolor}</h1>
);
}
}
ReactDOM.render(<Header/>, document.getElementById('root'));
ii)getDerivedStateFromProps()
->method is called right before rendering the element(s) in the DOM.
->eg:class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
static getDerivedStateFromProps(props, state) {
return {favoritecolor: props.favcol };
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));
iii)render()
->Output the HTML documents in the DOM.
->eg:class Header extends React.Component{
render(){
return(
<h1>This is the content of the header component</h1>
);
}
}
ReactDom.render(<Header />, document.getElementById('root'));
iv)componentDidMount()
->called after render() method
->eg:class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
b)Updating
->second phase in which component updated.
->five methods are called.
i)getDerivedStateFromProps()
->eg:class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
static getDerivedStateFromProps(props, state) {
return {favoritecolor: props.favcol };
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));
ii)shouldComponentUpdate()
->return boolean value, default value is true.
->eg:class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
shouldComponentUpdate() {
return false;
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
iii)render()
->It is always called when components gets updated.
->eg:class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
iv)getSnapshotBeforeUpdate()
->have access to the props and state before the update.
->to use this method, you should also include the componentDidUpdate()
->eg:class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
getSnapshotBeforeUpdate(prevProps, prevState) {
document.getElementById("div1").innerHTML =
"Before the update, the favorite was " + prevState.favoritecolor;
}
componentDidUpdate() {
document.getElementById("div2").innerHTML =
"The updated favorite is " + this.state.favoritecolor;
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<div id="div1"></div>
<div id="div2"></div>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
v)componentDidUpdate()
->called after the component is updated in the DOM.
->eg:class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
componentDidUpdate() {
document.getElementById("mydiv").innerHTML =
"The updated favorite is " + this.state.favoritecolor;
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<div id="mydiv"></div>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
c)Unmounting
->phase when the component is removed from DOM.
->one method only.
i)componentWillUnmount()
->called when component is about to remove
->eg:class Container extends React.Component {
constructor(props) {
super(props);
this.state = {show: true};
}
delHeader = () => {
this.setState({show: false});
}
render() {
let myheader;
if (this.state.show) {
myheader = <Child />;
};
return (
<div>
{myheader}
<button type="button" onClick={this.delHeader}>Delete Header</button>
</div>
);
}
}
class Child extends React.Component {
componentWillUnmount() {
alert("The component named Header is about to be unmounted.");
}
render() {
return (
<h1>Hello World!</h1>
);
}
}
ReactDOM.render(<Container />, document.getElementById('root'));