[go: up one dir, main page]

0% found this document useful (0 votes)
8 views187 pages

Sheeba React Js {Updated}

The document provides an overview of React JS, comparing it with Angular and Vue, highlighting its features as a JavaScript library for building user interfaces. It covers the installation process, the concept of Single Page Applications, the Virtual DOM, and the use of components, including functional and class components. Additionally, it discusses React props, ES6 features, and provides examples of code structure and styling in React applications.

Uploaded by

Hari Prasath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views187 pages

Sheeba React Js {Updated}

The document provides an overview of React JS, comparing it with Angular and Vue, highlighting its features as a JavaScript library for building user interfaces. It covers the installation process, the concept of Single Page Applications, the Virtual DOM, and the use of components, including functional and class components. Additionally, it discusses React props, ES6 features, and provides examples of code structure and styling in React applications.

Uploaded by

Hari Prasath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 187

React Js

Bala
React Vs Angular
• Angular is a Framework
▫ In Framework we have a ready made
Blocks
• React is a Library
▫ Here we need to Search and Use the
Blocks
Introduction to React Js
• React is a JavaScript Library for building
user interface created by Facebook
• It’s a “View” In MVC Patten
• React is an Open Source, Component-
based front end library responsible only
for the view layer of the application.
• React is used to build a single page
Application
Single Page Application
• A Single page application is a web application (or)
website that interacts with the web browser by
dynamically rewriting the current web page with
new data from the web server.

• Instead of the default method of the browser


loading entire new page

• The goal is faster transitions that make the


website feel more like a native app.
React JS Virtual DOM
• React creates a Virtual DOM in Memory.
• Manipulating Real DOM is much slower than manipulating
Virtual DOM
React Only Change What needs to be
changed!
Install Node JS & npm Set UP
• Install Node JS & npm for Using React Js in
Your System.
• Opensourse developer use npm to share
software. , Npm – Node Package Manager

• Npm is the world’s largest Software library


with 8 lakhs code packages.

• Npm is installed with Node Js


React Vs Angular
React Angular

1) React Developed by Facebook 1) Angular developed by Google


2) React is a JavaScript Library 2) Angular is a Framework
3) React Only focus on View in MVC
3) Angular completely focus on MVC
4) React is best for single page
4) Angular is best for single page applications
applications that update multiple views
that update single views at a time
at a time

5) React Support Unit Testing Only 5) Angular Support Unit & Integration Testing

6) React requires additional tools to 6) Angular manages dependencies


manage dependencies. automatically
7) React update only the Virtual DOM
7) Angular update the Real DOM
8) One way data binding
8) Two way data bindling
9) Compile time deugging
9) Realtime debugging
10) Used by Facebook,Paypal,
NetFlix,Instagram 10) Used by Google , Freelancer, Udemy,
React Vs Vue
React Vue
1) Vue Created by Laravel & Alibaba
1) React Developed by Facebook
2) Vue is a JavaScript Front end
2) React is a JavaScript Library
Framework
3) React provides great flexibility to
3) Vue provides Limited flexibility as
support third-party library
compared t0 React
4) It is used to develop interactive web
4) It is used to develop web based
application as well as mobile application application
5) React supports One way data binding 5) Vue support both One way & two
6) Speed is normal way data binding.

7) In React, State Management Library is 6) It is Faster & Smoother

Called MobX. 7) In Vue , State Management

8) Used by Facebook,Paypal, Library is Called VueX.

NetFlix,Instagram 8) Used by Alibaba, GitLab, MI Etc….


React Vs Node
React Node
1) Node is a JavaScript runtime
1) React library was developed in order to
environment that helps to
improve & enhance the UI for the web
execute the JavaScript outside
apps
the browser
2) React is basically used in client-side
2) Node is basically used in server
3) React is written y pure vanilla java Script
side
4) React support both Android & Web
3) Node written by C,C++ &
5) React support both Frontend & Server
JavaScript
side
4) Node only support web
6) React help to create east UI test cases
5) Node does not provide much
7) Used by Facebook, PayPal, Netflix,
support for front end
Instagram , etc
6) Node support server side test
case
7) Used by LinkedIn ,Uber, Github
Add React to Website using Script tags
• In the HTML page, right before the closing </body> tag, add
three <script> tags for the following files:

• react.development.js lets you define React components.


• react-dom.development.js lets React render HTML
elements to the DOM.

• Link : https://reactjs.org/docs/add-react-to-a-website.html

• <script
src="https://unpkg.com/react@18/umd/react.development.js"
crossorigin></script>

• <script src="https://unpkg.com/react-dom@18/umd/react-
dom.development.js" crossorigin></script>
React DOM Render
• The purpose of React DOM.render() function
is to display the specified HTML code inside
the specified HTML Element.

• This function takes two Arguments,HTML


code & HTML Element.
• For Ex:
• Const v =“Welcome to React Js”;
• ReactDOM.render(v,document.getElementB
yId(a‘’));
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://unpkg.com/react@18/umd/react.development.j

Index.html
s" crossorigin>
</script>
<script
src="https://unpkg.com/react-dom@18/umd/react-
dom.development.js" crossorigin></script>
<title>React Js</title>
</head>
<body>
<div id="a"></div>
<script src="reactjs.js"></script>
</body>
</html>

Reactjs.js
const v ="Welcome to React Js By Facebook...!"
ReactDOM.render(v,document.getElementById("a"));
Create React App
• Install Nodejs & npm (Works Both Online &
Offline)
• Installed with Node.js 8.10 above & npm
5.6 Above
• After installation goto Command Prompt:
▫ npx create-react-app my-app
• Npm install –g create-react-app my
app
▫ cd my-app
▫ npm start
Editing your react code in visual code editier :
Run the First App
• Goto Cmd :
• C:\Users\Bala>node --version
▫ v16.17.1
• C:\Users\Bala>npm --version
▫ 8.15.0
• C:\Users\Bala>npx create-react-app my-app
▫ Installing packages. This might take a couple of minutes.
▫ Installing react, react-dom, and react-scripts with cra-
template...

Creating a new React app in C:\Users\Bala\


myapp.
Edit with Visual Studio
GIT & GITHUB
• GIT is Version Control System, It’s Track
the code
• GITHUB : Cloud Storage

• To find Version = git –version


• To Initialized the Path of Project = git init
• To Track & the Element = git add .
• To Commit the Track = git commit –m
“First Commit”
• Move Project Remote URL = git remote
add origin ULR(your url)
• Upload = git push –u origin main
REACT ES6
• ES6 stands for ECMA Script 6 Version
• ECMA Script is the Standardization of
Javascript programming Language
• Use of ES6 features We Write less & Do
More
• Some of the features like :
▫ Classes
▫ Arrow Function
▫ Variables (Var,Let,Const)
Feature of ES6
• CLASS : A class is used to bind data as
well as methods together as a single unit.
Object acts like a variable of the class.
• ARROW : To write a shorter syntax for the
function we use ARROW
• VAR : if we use outside & Inside of the
function its act both global & local
variable
• CONST : Once we assign a variable as
constant we never change it
• LET : use inside & Outside Overcomming
the VAR problems
Index.js File
Ex : index.js file (CLASS)
import React from 'react';
import ReactDOM from 'react-dom';
class React_App {
addition()
{
var a = 5;
var b = 10;
document.getElementById('root').innerHTML =
a+b;
}

}
var mydemo = new React_App();
mydemo.addition();
Ex : index.js file (ARROW)
import React from 'react';
import ReactDOM from 'react-dom';
var x = function()
{
var a = 15;
var b = 15;
document.getElementById('root').innerHTML = a+b;
}
x();

import React from 'react';


import ReactDOM from 'react-dom';
var x = ()=>
{
var a = 15;
var b = 15;
document.getElementById('root').innerHTML = a+b;
}
x();
Ex : index.js file (ARROW)
import React from 'react';
import ReactDOM from 'react-dom';
var addition = (x) =>
{
var a = 5;
if(a==5)
{
let a = 10;
}
document.getElementById('root').innerHTML =
a;
}
addition(5);
React JSX
• This funny tag syntax is neither a String Nor
HTML.
• It is called JSX, and it is a syntax extension to
JavaScript.
• JSX may remind you of a template language, but it
comes with the full power of JavaScript.
▫ JSX stand code Vs Without JSX code
▫ Expressions in JSX
▫ Wrapping elements or Children in JSX
▫ Styling in JSX
▫ Attributes in JSX
▫ Comments in JSX
Without JSX Code

import React from 'react';


import ReactDOM from 'react-dom';

const myele = React.createElement('h1',{},"Welcome to React


Js")
ReactDOM.render(myele,document.getElementById('root'))

With JSX Code


import React from 'react';
import ReactDOM from 'react-dom';

const myele = <h1>Welcome to React JS</h1>


ReactDOM.render(myele,document.getElementById('root'))
Multi Comment Tags
import React from 'react';
import ReactDOM from 'react-dom';

const myele = <div>


<h1>Welcome to React JS</h1>
<h2>Multi Comment Tag</h2>
<p>Using Parent Variable's</p>
</div>

ReactDOM.render(myele,document.getElementById('ro
ot'))
React Using Inner CSS
import React from 'react';
import ReactDOM from 'react-dom';

var mystyle={
color : 'green',
textAlign : 'center'

}
const myele = <div style={mystyle}>
<h1>Welcome to React JS</h1>
<h2>Multi Comment Tag</h2>
<p>Using Parent Variable's</p>
</div>

ReactDOM.render(myele,document.getElementById('root'))
React Using External CSS Sheet
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
const myele = <div>
Index.Js
<h1 className='header'>Welcome to React JS</h1>
<h2 className='head'>Multi Comment Tag</h2>
<p className='head'>Using Parent Variable </p></div>
ReactDOM.render(myele,document.getElementById('root'))

.header{
color:green;
text-align: center;
}
.head{
Index.Css
color:brown;
text-align: center;
}
React Components
• Every application you will develop in React will be made up of
pieces called components.

• Components make the task of building UI much easier.

• We have lot of individual components like a single web page


contain (Search bar,menu bar, nav bar, content, article etc…)

• Merge all of these individual components to make a parent


component which will be the final UI

• Two types of Components:


Main Uses is Re- Usability of Code
▫ Functional Components

▫ Class Components
Functional Component
import React from 'react';
import ReactDOM from 'react-dom';

function Header(){
return <h1> Welcome to React Js</h1>
}
ReactDOM.render(<Header/
>,document.getElementById('root'))
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

function Header(){
Multi Functional
return <h1> Welcome to React Js</h1> Component
}

function Sidebar(){
return <h2> Sidebar</h2>
}

function Navbar(){
return <h2> Navbar</h2>
}

function Myweb(){
return <div>
<Header/>
<Sidebar/>
<Navbar/>
</div>
}
ReactDOM.render(<Myweb/
>,document.getElementById('root'))
Class Component
import React from 'react';
import ReactDOM from 'react-dom';

class Myweb extends React.Component


{
render(){
return <h1>Welcome to React Js</h1>
}
}
ReactDOM.render(<Myweb/
>,document.getElementById('root'))
import React from 'react';

class Myweb extends React.Component


{
render(){
return <h1>Welcome to React
Js</h1>
}
}
export default Myweb
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
Multi
class Myweb extends React.Component
{
Class
render(){ Component
return <h1 className='header'>Welcome to React Js</h1>
}
}

class Mywebsite extends React.Component


{
render(){
return <div>
<Myweb/>
<h2 className='head'>Class Component Example</h2>
<h3 className='head'>Multi Component</h3>
</div>
}
}
ReactDOM.render(<Mywebsite/>,document.getElementById('root'));
import React from 'react';

class Myweb extends


React.Component
{
render(){
return <h1>Welcome to React
Js</h1>
}
}

class Multi extends


React.Component
{
render(){
return <h1>Welcome to React Js
multi class components</h1>
}
}
class My extends React.Component
{
render(){
return(
<>
<Myweb/>
<Multi/>
</>
)}
}
export default My
Multi Class Component External File
“App.Js”
import React from 'react'; import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import './index.css'; import './index.css';
import Myweb from './App.js';
class Myweb extends React.Component
{
render(){
class Mywebsite extends React.Component return <h1 className='header'>Welcome to
{ React Js</h1>
render(){ }
return <div> }
export default Myweb;
<Myweb/>
<h2 className='head'>Class Component App.js
Example</h2>
<h3 className='head'>Multi Component</h3>
</div>
}
}
ReactDOM.render(<Mywebsite/
>,document.getElementById('root'))

index.js
• import React from 'react';

App.js
import './App.css';
class My extends import My from './class'
React.Component
•{ function App() {
• render(){ return (
• return <h1 <>

className='header'>Wel <My topic="sheeba"/>


come
</>
{this.props.topic}</h1>
);
• } }
•}
export default App;
• export default My
React Props – “Properties”
• Props stands for “Properties”
• React allows us to pass information to a
component using Props.
• Props are immutable so , we cannot modify the
props from inside the component.
• Props are basically kind of global variable or
object
• It’s an object which stores the value of attributes
of a tag and work similar to the HTML attributes.
• We can access any prop from inside a component
class using the below syntax.

▫this.props.propName;
Props Example

import React from 'react';


import ReactDOM from 'react-dom';
import './index.css';

class Myweb extends React.Component


{
render(){
return <h1 className='header'>Welcome {this.props.topic}</h1>
}
}

ReactDOM.render(<Myweb topic='to React Js -


"Properties"'/>,document.getElementById('root'))
import React from 'react';

class Myweb extends


React.Component
{
render(){
return(
<>
<h1 className='header'>Welcome
{this.props.topic}</h1>

</>
)}
}
export default Myweb

App.js - <Myweb
topic={"helooo"} />
import React from 'react';

function Myweb(props){
return(
<>
<h1> welcome to react
props {props.sheeba}</h1>
</>
)
}

export default Myweb

<Myweb sheeba={"sheeba"}/>
Multi Props Example

import React from 'react';


import ReactDOM from 'react-dom';
import './index.css';

class Myweb extends React.Component


{
render(){
return <h1 className='header'>Welcome {this.props.topic} in
{this.props.lang}</h1>

}
}

ReactDOM.render(<Myweb topic='to React Js - "Properties"'


lang='JavaScript'/>,document.getElementById('root'))
import React from 'react';

class Myweb extends


React.Component
{
render(){
return(
<>
<h1 className='header'>Welcome
{this.props.topic}
{this.props.name}</h1>

</>
)}
}
export default Myweb

app.js - <Myweb topic={"helooo"}


name={"sheeba"}/>
import React from 'react';

function Myweb(props){
return(
<>
<h1> welcome to react
props {props.name}{props.age}
{props.value}</h1>
</>
)
}

export default Myweb

<Myweb
name={"sheeba"}age={23}
value={"react"}/>
Passing Component one to another Class
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
class Myweb extends React.Component
{
render(){
return <h1 >Welcome to {this.props.var}</h1>
}
}

class Myweb2 extends React.Component


{
render(){
const v="Web Development";
return<Myweb var={v}/>
}
}
export default Myweb2
import React from 'react';

class Myweb extends


React.Component
{
render(){
return <h1
className='header'>Welcome to
{this.props.var}</h1>
}
}
class Myweb2 extends
React.Component
{
render(){
const v="Web Development";
return<Myweb var={v}/>
}
}

export default Myweb2


Passing Component one to another Class
using object
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
class Myweb extends React.Component
{
render(){
return <h1 className='header'>Welcome to
{this.props.var.lang} {this.props.var.concept}</h1>
}
}

class Myweb2 extends React.Component


{
render(){
const v={var:"Web Development",lang:"Lang :
Reactjs",concept:"Concents : Props"}
return<Myweb var={v}/>
}
}
import React from 'react';

class Myweb extends


React.Component
{
render(){
return <h1
className='header'>Welcome to
{this.props.var.lang}
{this.props.var.concept}</h1>
}
}
class Myweb2 extends React.Component
{
render(){
const v={lang:"Lang :
Reactjs",concept:"Concents : Props"}
return<Myweb var={v}/>
}
}

export default Myweb2


Call Default Props in Main Class

import React from 'react';


import ReactDOM from 'react-dom';
import './index.css';
class Myweb extends React.Component
{
render()
{
return <h1 className='header'>Welcome to
{this.props.concept} in {this.props.Lang}</h1>
}
}
Myweb.defaultProps={concept:"props",Lang:"ReactJs"}
ReactDOM.render(<Myweb concept="Component Vs
State"/>,document.getElementById('root'));
import React from 'react';

class Myweb extends


React.Component
{
render()
{
return <h1
className='header'>Welcome to
{this.props.concept} in
{this.props.Lang}</h1>
}
}
Myweb.defaultProps={concept:"pro
ps",Lang:"ReactJs"}

export default Myweb

App.js --<Myweb
concept={"Component Vs State"}/>
React State
• React Components has a built-in state object.
• To define a state, you have to first default set of value for
defining the component’s initial state.
• To do this, add a class constructor which assigns an initial
state using this.state
• The “this.state” property can be rendered inside render()
method.
 this.state.statename

• If you want to change a value in the state object, use the


below method
 this.setstate()


React State
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
class Myweb extends React.Component
{
constructor(){
super();
this.state={initalvalue:"Welcome"}
}
render(){
return <h1>{this.state.initalvalue}</h1>
}
}
ReactDOM.render(<Myweb/>,document.getElementById('root'))
import React from "react";

class Myweb extends


React.Component
{
constructor(){
super();
this.state={initalvalue:"Welcom
e"}
}
render(){
return
<h1>{this.state.initalvalue}</h1
>
}
}
export default Myweb
import React, { useState } from 'react';

function Myweb() {
const [initalvalue] = useState("Welcome");

return <h1>{initalvalue}</h1>;
}

export default Myweb;


Multi State - React
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
class Myweb extends React.Component
{
constructor(){
super();
this.state={initalvalue:"Welcome",name:" to React State "}
}
render(){
return <h1>{this.state.initalvalue}{this.state.name}</h1>
}
}
ReactDOM.render(<Myweb/>,document.getElementById('root'))
import React from 'react';
function Myweb() {
const initalvalue = "Welcome";
const name = " to React State ";

return
<h1>{initalvalue}{name}</h1>;
}
export default Myweb;
import React, { useState } from
'react';

function Myweb() {
const [state] = useState({
initalvalue: "Welcome",
name:"to React State "
});

return <h1>{state.initalvalue}
{state.name}</h1>;
}
export default Myweb;
class Myweb extends React.Component
{
constructor(){
super();
this.state={initalvalue:"Welcome",nam
e:"sheeba",}
}
render(){
return <h1>{this.state.initalvalue}
{this.state.name}</h1>
}
}
export default Myweb
import React from "react";

const MyWeb = () => {

const [initialValue]
="Welcome";
const [name]="sheeba";
return (
<div>

<h1>{initialValue},{name}</h1>
</div>
);
};

export default MyWeb;


setState to Replace the Initial
value Base class
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
class Myweb extends React.Component
{
constructor(){
super();
this.state={initalvalue:"Welcome to",name:" React State "}
}
changevlaue=()=>
{
this.setState({initalvalue:"Get Start to Learn"});
}
render(){
return <div>
<h1>{this.state.initalvalue}{this.state.name}</h1>
<br/>
<button type='button'onClick={this.changevlaue}> Exit</button>
</div>
}}
ReactDOM.render(<Myweb/>,document.getElementById('root'))
import React from "react";
class Myweb extends
React.Component
{
constructor(){
super();

this.state={initalvalue:"Welcome
to",name:" React State "}
}
changevlaue=()=>
{

this.setState({initalvalue:"Get
Start to Learn"});
}
render(){
return <div>
<h1>{this.state.initalvalue}
{this.state.name}</h1>
<br/>
<button
type='button'onClick={this.changevl
aue}> Exit</button>
</div>
} }
export default Myweb;
import React, { useState } from
"react";

const MyWeb = () => {

const [initialValue,
setInitialValue] =
useState("Welcome to");
const [name] = useState("
React State");

const changeValue = () => {


setInitialValue("Get Start
to Learn");
};
return (
<div>
<h1>{initialValue}
{name}</h1>
<br />
<button type="button"
onClick={changeValue}>
Exit
</button>
</div>
);
};

export default MyWeb;


Props Vs State
Props State

• Props are Not Changeable • State is Changeable


component component .
• Props allow you to pass data
• State holds information
from one component to other
about the components
components as an argument
• State cannot be accessed
• Props can be accessed by the
by child components
child components
• Props are used to • States can be used for

communicate between rendering dynamic change


components with the components
React “this” Keyword
• Regular Function:
▫ The “this” represents the object that
called the function.
▫ It means there is an different objects
depending on how the function was called,
which could be the window, document ,
button or Whatever…
• Arrow Function:
▫ The “this” keyword always represent the
object that defined the arrow function.
▫ No matter who called function.
Accessing State

import React from "react";


class MyComponent extends React.Component {
constructor() {
super();
this.state = { message: 'Hello, React!' };
}

render() {
return <h1>{this.state.message}</h1>;
}
}

export default MyComponent;


Updating State
import React from "react";
class MyComponent extends React.Component {
constructor() {
super();
this.state = { message: 'Hello, React!' };
}

updateMessage = () => {
this.setState({ message: 'State Updated!' });
};

render() {
return (
<div>
<h1>{this.state.message}</h1>
<button onClick={this.updateMessage}>Update
Message</button>
</div>
);
}
}
export default MyComponent
this in Functional Components

import React, { useState } from 'react';

function MyComponent() {
const [message, setMessage] = useState('Hello,
React!');

const updateMessage = () => {


setMessage('State Updated!');
};

return (
<div>
<h1>{message}</h1>
<button onClick={updateMessage}>Update
Message</button>
</div>
);
}
export default MyComponent
React List

• List are used to display date in an ordered


format & mainly used to display menus on
websites like navigation bar, menu bar etc…

• Let us now create a list of elements in react

• To do this, we will traverse the list using the


javascript map() function & update elements
to be enclosed between <li></li> Tag.

• Finally we will warp this new list within


<ul></ul> Tag & render it the DOM
Simple React List

import React from 'react';

import ReactDOM from 'react-dom';

const newlist = [10,20,30,40,50]

const rl = newlist.map((listvalues) =>{

return <li>{listvalues}</li>

});

ReactDOM.render(<ul>{rl}</ul>,document.getElementById('root'));

import React from 'react';


import ReactDOM from 'react-dom';

const newlist = [10,20,30,40,50]


const rl = newlist.map((listvalues) =>{
return <li>{listvalues+" - "+newlist}</li>
});
ReactDOM.render(<ul>{rl}</ul>,document.getElementById('root'));
import React from "react";
function Menubar()
{
const newlist = [10,20,30,40,50]
const rl = newlist.map((listvalues)
=>{
return <li>{listvalues}</li>
});
return<ol>{rl}</ol>
}
export default Menubar;
import React from 'react';

function NumberList() {
const newlist = [10, 20, 30, 40, 50];

const rl = newlist.map((listvalues, index)


=> (
<li key={index}>
{listvalues + " - " + newlist}
</li>
));

return (
<div>
<h3>Number List:</h3>
<ul>{rl}</ul>
</div>
);
}

export default NumberList;


List Value passing inside Function
import React from 'react';
import ReactDOM from 'react-dom';

function Menubar()
{
const newlist = [10,20,30,40,50]
const rl = newlist.map((listvalues) =>{
return <li>{listvalues}</li>
});
return<ul>{rl}</ul>
}
ReactDOM.render(<Menubar
newlist/>,document.getElementById('root'));
List Value passing using Props
import React from 'react';
import ReactDOM from 'react-dom';

function Menubar(props)
{
const myvalue =props.myvalue;
const rl = myvalue.map((listvalues) =>{
return <li>{listvalues}</li>
});
return<ul>{rl}</ul>
}
const myvalue = [10,20,30,40,50]
ReactDOM.render(<Menubar myvalue={myvalue
}/>,document.getElementById('root'));
React Keys
• A “Key” is a Special string attribute you
need to include when creating Lists of
elements in React.

• Key are used in React to identify which


items in the List are changed, updated or
deleted.

• It also helps to determine which


components in a collection needs to be re-
import React from 'react';

function FruitList() {
const fruits = ['Apple', 'Banana',
'Cherry', 'Mango'];

return (
<div>
<h3>Fruit List:</h3>
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
</div>
);
}

export default FruitList;


import React from 'react';

function CityList() {
const cities = ['Delhi', 'Mumbai', 'Chennai',
'Kolkata'];

return (
<div>
<h2>List of Cities:</h2>
<ul>
{cities.map((city, index) => (
<li key={index}>{index + 1}. {city}</li>
))}
</ul>
</div>
);
}

export default CityList;


import React from 'react';

function CountryList() {
const countries = ['India', 'USA', 'Canada',
'Australia'];

return (
<div>
<h2>List of Countries:</h2>
<ul>
{countries.map((country) => (
<li key={country}>{country}</li>
))}
</ul>
</div>
);
}

export default CountryList;


“Key” Example

import React from 'react';


import ReactDOM from 'react-dom';

function Menubar(props){
const content = props.data.map((show) => 3
<div key={show.id}>
<h3>{show.id}:{show.title}:{show.content}</h3>
</div>
);
return(
4
<div>
{content}
</div>
);
}
const myvalue =[
1
{id: 1, title: 'First', content: 'Welcome to React Programmning'},
{id: 2, title: 'Second', content: 'React Developed by Facebook'},
];
ReactDOM.render(<Menubar data={myvalue}/>,
2
document.getElementById('root')
5
);
List with “Key” Example using index
number
import React from 'react';
import ReactDOM from 'react-dom';
function ListKey(props){ //6
const item = props.item; // 7
const key =props.keys; //8
return(
<li>Key {key} : Item {item}</li> //9
); }

function MyList(props){ // 3
const listItem = props.myvalue.map((listvalue,index) => // 4 // 10
<ListKey keys ={index} item={listvalue}/> // 5
);
return( // 11
<div>
<h2>Correct Key Usae Example</h2>
<ul>{listItem}</ul>
</div>
); }
const mydata =[200,1000,5000,300]; // 1
ReactDOM.render(<MyList myvalue={mydata}/>, // 2
document.getElementById('root') // 12
);
List with “Key” Example using Value
import React from 'react';
import ReactDOM from 'react-dom';
function ListKey(props){ //6
const item = props.item; // 7
const key =props.keys; //8
return(
<li>Key {key} : Item {item}</li> //9
); }

function MyList(props){ // 3
const listItem = props.myvalue.map((listvalue) => // 4 // 10
<ListKey keys ={listvalue} item={listvalue}/> // 5
);
return( // 11
<div>
<h2>Correct Key Usae Example</h2>
<ul>{listItem}</ul>
</div>
); }
const mydata =[200,1000,5000,300]; // 1
ReactDOM.render(<MyList myvalue={mydata}/>, // 2
document.getElementById('root') // 12
);
React Lifecycle
• In React Every Components has various
Lifecycle methods.
• All the Lifecycle methods are comes under
the four phases.

1. Initial Phase
2. Mounting Phase
3. Updating Phase
4. Unmounting Phase
Initial Phase
• In this phase the developer has to define the props
& initial state of the component this is generally
done in the constructor of the component.
• getDefaultProps():
• It is used to specify the default value of this.props.
Its invoked before the creation of the component.

• getInitialState()
• Its used to specify the default value of this.state. Its
invoked before the creation of the component.
Mounting Phase
• After the initialization of the component is
completed, then the component is mounted on
the DOM & rendered for the first time in the
web page.
• componentWillMount() Function: this
function is invoked before the component is
mounted on the DOM. (setState())

• componentDidMont() Function: this function


is invoked after the component is mounted on
the DOM
Updating Phase
• Updation is the phase where the states and
props of a component are updated followed
by some user events such as click or
pressing button
• componentWillUpdate() Function:
▫ Before component is re-rendered
• componentDidUpdate() Function:
▫ After component is re-rendered
• Render()
• ShouldComponentUpdate()
Unmounting Phase
• componentWillUnmount():
▫ This method is invoked immediately before
a component is destroyed & Un-mounted
permanently.
Without LifeCycle Methods

import React from 'react';


import ReactDOM from 'react-dom';

class Lifecucle extends React.Component


{
constructor(){
super();
this.state={value:'Welcome to',name:'Pumo Tech'}
}
render(){
return<h1>{this.state.value} {this.state.name}</h1>
}
}
ReactDOM.render(<MyList
myvalue={mydata}/>,document.getElementById('root')
);
ComponentWillMount
import React from 'react';
import ReactDOM from 'react-dom';

class Lifecycle extends React.Component


{
constructor(){
super();
this.state={value:'Welcome to',name:'Pumo Tech'}
}
componentWillMount()
{
alert('Learn ReactJS Lifecycle in Pumo Tech');
}
render(){
return<h1>{this.state.value} {this.state.name}</h1>
}
}
ReactDOM.render(<Lifecycle/>,document.getElementById('root'));
import React, { useEffect, useState } from 'react';
function Lifecycle() {
const [state] = useState({
value: 'Welcome to',
name: 'Pumo Tech'
});

useEffect(() => {
// This runs once like componentWillMount (but
safely after render)
alert('Learn ReactJS Lifecycle in Pumo Tech');
}, []);

return (
<h1>{state.value} {state.name}</h1>
);
}

export default Lifecycle;


ComponentDidMount
import React from 'react';
import ReactDOM from 'react-dom';

class Lifecycle extends React.Component


{
constructor(){
super();
this.state={value:'Welcome to',name:'Pumo Tech'}
}
componentWillMount()
{
alert('Learn ReactJS Lifecycle in Pumo Tech');
}
render(){
return<h1>{this.state.value} {this.state.name}</h1>
}

componentDidMount()
{
setTimeout(() =>{
this.setState({value:"Thank You"})},5000)
}
}
ReactDOM.render(<Lifecycle/>,document.getElementById('root'));
import React, { useState,
useEffect } from 'react';

function Lifecycle() {
const [state, setState] =
useState({
value: 'Welcome to',
name: 'Pumo Tech'
});

// Equivalent to
componentWillMount (called
before first render)
useEffect(() => {
alert('Learn ReactJS
Lifecycle in Pumo Tech');
}, []);
useEffect(() => {
const timer = setTimeout(()
=> {
setState(prev => ({
...prev,
value: 'Thank You'
}));
}, 3000);

return () =>
clearTimeout(timer); // cleanup
}, []);

return (
<h1>{state.value}
{state.name}</h1>
);
}

export default Lifecycle;


import React from 'react';
import ReactDOM from 'react-dom';
Update
class Lifecycle extends React.Component
{
constructor(){
super();
this.state={value:'Welcome to',name:'Pumo Tech'}
}
componentWillMount()
{
alert('Learn ReactJS Lifecycle in Pumo Tech');
}
render(){
return <div>
<h1>{this.state.value} {this.state.name}</h1>
<br/>
<button type="button" onClick={this.changevalue}>Change Value</button>
</div>
}
changevalue = () =>
{
this.setState({value:"Get Update with"});
}

componentDidMount()
{
setTimeout(() =>{
this.setState({value:"Thank You"})},5000)
}
componentWillUpdate(){
alert("Do you Want Update a New Value");
}
}
ReactDOM.render(<Lifecycle/>,document.getElementById('root'));
import React from 'react';
import ReactDOM from 'react-dom';

class Lifecycle extends React.Component

DidUpda
{
constructor(){
super();
this.state={value:'Welcome to',name:'Pumo Tech'}
}
componentWillMount()
{
alert('Learn ReactJS Lifecycle in Pumo Tech');
te
}
render(){
return <div>
<h1>{this.state.value} {this.state.name}</h1>
<br/>
<button type="button" onClick={this.changevalue}>Change Value</button>
</div>
}
changevalue = () =>
{
this.setState({value:"Get Update with"});
}
componentDidMount()
{
setTimeout(() =>{
this.setState({value:"Thank You"})},5000)
}
componentWillUpdate(){
alert("Do you Want Update a New Value");
}
componentDidUpdate()
{
document.getElementById("mydiv").innerHTML="NEW VALUE UPDATED SUCESSFULLY"+this.state.value;
}
}
ReactDOM.render(<Lifecycle/>,document.getElementById('root'));
import React from 'react';
import ReactDOM from 'react-dom';

class Lifecycle extends React.Component


{
constructor(){
super();
shouldComponentUpdat
this.state={value:'Welcome to',name:'Pumo Tech'}
}
componentWillMount()
e()
{
alert('Learn ReactJS Lifecycle in Pumo Tech');
}
render(){
return <div>
<h1>{this.state.value} {this.state.name}</h1>
<br/>
<button type="button" onClick={this.changevalue}>Change
Value</button>
</div> componentWillUpdate(){
} alert("Do you Want Update a New Value");
changevalue = () => }
componentDidUpdate()
{
{
this.setState({value:"Get Update with"}); document.getElementById(“root").innerHTML="NEW
} VALUE UPDATED SUCESSFULLY"+this.state.value;
}
componentDidMount() shouldComponentUpdate(){
{ return true; // false
setTimeout(() =>{ }
this.setState({value:"Thank You"})},5000)
}
} ReactDOM.render(<Lifecycle/
>,document.getElementById('root'));
import React from 'react';
import ReactDOM from 'react-dom';

class Lifecycle extends React.Component


{
constructor(){
super();
this.state={value:'Welcome to',name:'Pumo Tech'}
} WillUnMount()
componentWillMount()
{
alert('Learn ReactJS Lifecycle in Pumo Tech');
}
render(){ componentWillUpdate(){
alert("Do you Want Update a New Value");
return <div>
}
<h1>{this.state.value} {this.state.name}</h1> componentDidUpdate()
<br/> {
<button type="button" onClick={this.changevalue}>Change document.getElementById(“root").innerHTML="NEW
Value</button> VALUE UPDATED SUCESSFULLY"+this.state.value;
<button type="button" onClick={this.deleteheader}>Delete }
Header</button> shouldComponentUpdate(){
</div> return true; // false
}
}
Deleteheader=() =>
changevalue = () => {
{ this.setState({value:false.name:false});
this.setState({value:"Get Update with"}); }
} componentWillUnmount()
{
alert(“Header Deleted”);
componentDidMount()
}
{
setTimeout(() =>{ }
this.setState({value:"Thank You"})},5000) ReactDOM.render(<Lifecycle/
} >,document.getElementById('root'));
React Event Handling
• An event is an action that could be triggered as a
result of the user action or system generated
event.

• For example, a mouse click, loading of a web


page, pressing a key, window resizes, and
other interactions are called events.

• React events are named using camelCase, rather


than lowercase.

• In React ,with help of JSX you pass a function as


the event handler, rather than a string.
• onClick={shoot} instead of onclick=“shoot()”
Possible Way of Event Handling
• Using the event method in class
component.
• Using bind keyword in event.
• Passing arguments to event using arrow
function.
• Passing arguments to event using bind.
Error Code : “this keyword is not working in normal
function”
import React from 'react';
import React from 'react';
import ReactDOM from 'react-dom';
import ReactDOM from 'react-dom';
class Eventbind extends React.Component{
class Eventbind extends React.Component{
constructor(){
constructor(){
super() super()
this.state={ this.state={
msg:"Welcome" msg:"Welcome"
} }
} }
clickEvent(){ clickEvent =() => {
this.setState({ this.setState({
msg:"Thank You" msg:"Thank You"
}) })
} }
render() render()
{ {
return( return(
<div> <div>
<h1>{this.state.msg}</h1> <h1>{this.state.msg}</h1>
<button <button onClick={this.clickEvent}>Click</button>
onClick={this.clickEvent}>Click</button> </div>
</div> )
) }
}
}
ReactDOM.render(<Eventbind/
}
>,document.getElementById('root'));
Argument Passing in Event
Handling uisng =>
import React from 'react';
import ReactDOM from 'react-dom';

class Eventbind extends React.Component{


constructor(){
super()
this.state={
msg:"Welcome"
}
}
clickEvent =(a) =>{
this.setState({
msg:a
})
}
render()
{
return(
<div>
<h1>{this.state.msg}</h1>
<button onClick={()=>this.clickEvent("Learn React Js")}>Click</button>
</div>
)
}
}
ReactDOM.render(<Eventbind/>,document.getElementById('root'));
Argument Passing in Event Handling
using Bind
import React from 'react';
import ReactDOM from 'react-dom';

class Eventbind extends React.Component{


constructor(){
super()
this.state={
msg:"Welcome"
}
}
clickEvent =(a) =>{
this.setState({
msg:a
})
}
render()
{
return(
<div>
<h1>{this.state.msg}</h1>
<button onClick={this.clickEvent.bind(this,"Learn React
Js")}>Click</button>
</div>
)
}
}
ReactDOM.render(<Eventbind/>,document.getElementById('root'));
React Vs
Redux
Why we use redux in react ? Ex : CRM
• Redux is an open-source JavaScript library for managing
application state Main Page (Sign
and building user interfaces . Up)
• You can write Redux apps with React, Angular, Ember, jQuery, or Greeting Page
vanilla (with Sign Up
JavaScript. Name)
• If you have few components in your application, With the help of
props,
we can pass these variables from parent component to various
other
components (child components) . Thank you Page
(with Sign Up
• But as the number of components increases in the application , if Name)
we need
to pass these props to other components located far away from
each
other in the component tree.

• At this moment, the usual way of transferring state as props to be


Redux : Methods
( Action , Reducers , Store , View )

• Actions - Actions have a type of fields that tells what kind


of action to perform. It includes information such as type of
action, time of occurrence, location of occurrence, its
coordinates, and which state it aims to change.

• Reducers - Actions only tell what to do, but they don’t tell
how to do, so reducers are the functions that take the
current state and action and return the new state and tell
the store how to do.

• Store - The store contains the state of the components


which need to be passed to other components.

• View − The view will receive data from the store and re -
render the app.
Redux Architecture

Contains State Defines

Store UI

Updates Triggers

Reduc Action
er s

Sent to
npm install redux
react-redux
Methods
• createStore()
• getState()
• dispatch()
• subscribe()
Concepts:
• State:
• The single source of truth for your
application.

• It's an immutable object that represents


the current state of your application.

• Changes to the state are made by


dispatching actions.
Actions:
•Plain JavaScript objects that describe the
type of change to be made to the state.

•They typically contain a type property to


identify the
action and any additional data needed
for the update.
• Reducers:
• Pure functions that take the current state
and an action as input and return a new
state.
• The reducer determines how the state
changes in response to actions.
import { createStore } from 'redux';

// Initial state
const initialState = {
count: 0
};

// Reducer function
function counterReducer(state =
initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { ...state, count:
state.count + 1 };
case 'DECREMENT':
return { ...state, count:
state.count - 1 };
default:
return state;
}
}
// Create the store

const store = createStore(counterReducer);

// Dispatch actions to update the state


store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });

// Get the current state

const currentState = store.getState();


console.log(currentState); // Output: { count:
1}
React SASS
• Sass - Syntactically Awesome Stylesheet

• Sass reduces repetition of CSS and therefore saves time.

• Sass have lot of features that do not exist in CSS, like variables, nested rules, imports,

inheritance, built-in functions etc;

• Install Sass in your React App by running this command in your terminal

• npm install node-sass

• Sass files has the ".scss" file extension.

• Sass uses the $ symbol, followed by a name, to declare variables

$variablename: value;

• A browser does not understand Sass code. Therefore, you will need a Sass

• pre-processor to convert Sass code into standard CSS. This process is called

transpiling.

• Transpiling is a term for taking a source code written in one language and

transform/translate it into another language.


• After install SASS Pack
npm install
sass
Create a Sass file with the .scss
extension
• $primary-color: #4caf50;
• $sheeba:red;

body {
• font-family: Arial, sans-serif;
• background-color: $primary-color;
• color: white;

h1 {
• text-align: center;
• color: $sheeba;
• }
•}
Create a .scss File

import React from "react";


import "./she.scss";

function Sheeba(){
return(
<>
<h1> heloo sheebaa welcome</h1>
</>
)
}
export default Sheeba
• import './App.css';
• import Sheeba from './sheeba';

function App() {
• return (
• <>
• <Sheeba/>
• </>
• );
•}

export default App;
React Forms
• Forms play a major role in any website for login , signup
etc;

• In React Forms work little different.

• In HTML, form data is usually handled by the DOM.

• In HTML elements like input tag, the value of the input field
is changed whenever the user type.

• In React, form data is usually handled by the components.

• But, In React, whatever the value user types we save it in


state and pass the same value to the input tag as its value,
so here its value is not changed by DOM, it is controlled by
react state.
import React from 'react'; React Forms
import ReactDOM from 'react-dom';

class Reactforms extends React.Component{


constructor(){
super()
this.state={username:""}
}
uservalue = (event) =>
{
this.setState({username:event.target.value});
}
render()
{
return(
<form>
<h1>Hello {this.state.username}!</h1>
Enter your name : <input type="text" onChange={this.uservalue}/>
<h3>Thank You !</h3>
</form>
) }
}
ReactDOM.render(<Reactforms/>,document.getElementById('root'));
React Forms Multiple inputs

import React from 'react';


import ReactDOM from 'react-dom';

class Reactforms extends React.Component{


constructor(){
super()
this.state={username:"",
age:null,
errmsg:""};
}
uservalue = (event) =>
{
let n=event.target.name;
let v=event.target.value;
let err=" ";
if(n ==="age"){
if(v!=="" && !Number(v)){
err = <strong> Invalid Value, Your age must be a
number</strong>
}
his.setState({errmsg:err});
his.setState({[n]:v});

ender()

eturn(
<form>
<h1>Hello {this.state.username}!</h1>
<h2>Your Age is {this.state.age}!</h2>
Enter your name : <input type="text" name="username" onChange={this.uservalue} />
Enter your age : <input type="text" name="age" onChange={this.uservalue}/>{this.state.errmsg}
<h3>Thank You !</h3>
</form>

actDOM.render(<Reactforms/>,document.getElementById('root'));
import React from 'react';
import ReactDOM from 'react-dom';

class Reactforms extends React.Component{


constructor(){
super()
this.state={username:"",
age:null,
React Forms
errmsg:""}; Multiple inputs
} with Submit
uservalue = (event) =>
{
let n=event.target.name;
let v=event.target.value;
let err=" ";
if(n ==="age"){
if(v!=="" && !Number(v)){
err = <strong> Invalid Value, Your age must be a
number</strong>
}
}
this.setState({errmsg:err});
this.setState({[n]:v});
formsubmit = (event) =>
{
event.preventDefault();
alert("Your Name: "+this.state.username);
}
render()
{
return(
React Forms
<form onSubmit={this.formsubmit}> Multiple inputs
<h1>Hello {this.state.username}!</h1> with Submit
<h2>Your Age is {this.state.age}!</h2>
Enter your name : <input type="text" name="username"
onChange={this.uservalue} />
Enter your age : <input type="text" name="age"
onChange={this.uservalue}/>{this.state.errmsg}
<input type="submit"/>
<h3>Thank You !</h3>
</form>

)
}
}
ReactDOM.render(<Reactforms/
React Fragments
• In React, whenever you want to render something on the
screen, you need to use a render method inside the
component.

• The render method will only render a single root node inside
it at a time.

• However, if you want to return multiple elements, the


render method will require a 'div' tag and put the entire
content or elements inside it.

• This extra node to the DOM sometimes results in the wrong


formatting of your HTML output and its not good semantic
html code.

• Advantage of using react fragments is it take lesser memory


and quicker execution.
Simple Fragment Example

import React from 'react';


import ReactDOM from 'react-dom';

class FragmentTab extends React.Component{


render(){
return(
<React.Fragment>
<h1> Welcome to React Js</h1>
<h2>React Fragment Example !</h2>
</React.Fragment>
)
}
}
ReactDOM.render(<FragmentTab/>,document.getElementById('root'));
Fragment with Class , Inheritance
import React from 'react';
import ReactDOM from 'react-dom';

class FragmentTab extends


React.Component{
render(){
return(
<table>
<tr>
<Rowcreation/>
</tr> class Rowcreation extends React.Component{
</table> render(){
return(
<React.Fragment>
) <td>Hello!</td>
} <td>Welcome to React Fragment Example !</td>
} </React.Fragment>
)
}
}
ReactDOM.render(<FragmentTab/
>,document.getElementById('root'));
React Hooks
• React Hooks allows you to use state and other React features
without writing a class.
▫ It does not work inside classes .
▫ Its work inside the function only.

Rules of Hooks :

1. Only call Hooks at the top level, Do not call Hooks


inside loops, conditions, or nested functions. Hooks
should always be used at the top level of the React
functions.

2. Only call Hooks from React functions You cannot call


Hooks from regular JavaScript functions. Instead, you can call
Hooks from React function components. Hooks can also be
called from custom Hooks.

3. Types : Hook State & Hook Effects


React Hook State

• Hook state is the new way of declaring a state in


React app.
• Hook uses useState() functional component for
setting and retrieving state.
• useState is the Hook which needs to call inside a
function component to add some local state to it.
• The useState returns a pair where the first
element is the current state value/initial value,
and the second one is a function which allows us
to update it.
• After that, we will call this function from an event
handler or somewhere else.
• The useState is similar to this.setState in class.
import React, { useState} from 'react';
import ReactDOM from 'react-dom';

function ReactHooks(){ //2


const [count, updateCount] = useState(0); //3
return (
<div>
<h1>You clicked the button {count} times</h1> React
<button onClick={() => updateCount(count + 1)}> Hook
Click Me
State
</button>
</div>
);
}
ReactDOM.render(<ReactHooks />,
document.getElementById('root')); //1
React Hooks Effect
• The Effect Hook allows us to perform side
effects (an action) in the function
components.
• It does not use components lifecycle
methods
• which are available in class components.
• Effects Hooks are equivalent to
▫ componentDidMount(),
▫ componentDidUpdate(),
▫ componentWillUnmount()
import React, { useState,useEffect } from 'react';
import ReactDOM from 'react-dom';

function ReactHooks(){
//2
const [count, updateCount] = useState(0);
//3
useEffect(() =>{
//4

})
alert("React Hook State Counter Program !");
React Hooks
Effect
return (
<div>
<h1>You clicked the button {count} times</h1>
<button onClick={() => updateCount(count + 1)}>
Click Me
</button>
</div>
);
}
ReactDOM.render(<ReactHooks />,
React Router

• React Router is mainly used for developing a Single


Page Web Applications. It plays an important role to
display multiple views in a single page application.

• Routing is a process in which a user is directed to


different pages based on their action or request.

• When a user types a specific URL into the browser,


and if the URL path matches any 'route' inside
the router file, the user will be redirected to that
particular route.

• Most of the social media websites like Facebook,


Instagram uses React Router for rendering multiple
views.
React Router Installation
• React Router is a standard library system . If you want to
create routing in the React application using React Router
Package.

• It is not possible to install react-router directly in your


application. To use react routing, first, you need to install
react-router-dom modules in your application. The below
command is used to install react router dom.

• $ npm install react-router-dom


• react-router-dom: It is used for web applications design.
import { Browser Router as Router, Route, Link, NavLink, Switch }

• Route - is the conditionally shown component based on matching a path


to a URL.

• BrowserRouter - is the router implementation It uses HTML5 history


API (i.e. pushState, replaceState and popState API) to keep your UI
in sync with the URL.

• Memory Router: Memory router keeps the URL changes in memory


not in the user browsers. It does not read or write to the address bar so
the user can not use the bowser’s back button as well as the forward
button. It is very useful for testing and non-browser environments like
React Native.

• Link - is your replacement for anchor tags. Sometimes, we want to


need multiple links on a single page. This <Link> component is used to
create links which allow to navigate on different URLs and render its
content without reloading the webpage.

• NavLink - component is used to add styles to the active routes and add
properties activeStyle. The activeStyle properties mean when we click
on the Link, it should have a specific style so that we can differentiate
which one is currently active page.
import
{ BrowserRouter,
Routes,Route } from
'react-router-dom';
App.js

<BrowserRouter>
<Routes>

<Route path='/' element={<Home/>}></Route>


<Route path='/about'
element={<About/>}></Route>
<Route path='/contact'
element={<Contact/>}></Route>
</Routes>
</BrowserRouter>
Home.js

import Navbar from "./navbar"

export default function Home(){


return(
<>

<Navbar/>
<h1> hai i am home page</h1>

</>
)
}
About.js

export default function About(){


return(
<h1> hai ia m About page</h1>
)
}
Contact.js

export default function Contact(){


return(
<h1> hai ia m contact page</h1>
)
}
Navbar.js

import React from "react";


import { Link } from "react-router-dom";
export default function Navbar(){
return(
<>
<div className="d-flex flex-row justify-content-around">
<Link to='/'><p>sheeba1</p></Link>
<Link to='/about'><p>sheeba2</p></Link>
<Link to='/contact'><p>sheeba3</p></Link>
<Link to='/'><p>sheeba4</p></Link>
<Link to='/about'>karthii</Link>

</div>

</>
)
}
import React from 'react';
import ReactDOM from 'react-dom'; Index.js
import{BrowserRouter as Router,Route,Link,NavLink,Switch} from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';

const routing = (
<Router>
<div>
<h1> React Router Example </h1>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/">About</Link>
</li>
<li>
<Link to="/">Contact</Link>
</li>
</ul>
<Route path="/"component={Home}/>
<Route path="/abt"component={About}/>
<Route path="/con"component={Contact}/>
</div>
</Router>
) ReactDOM.render(routing,document.getElementById('root'));
About.js
import React from 'react';
import ReactDOM from 'react-dom';

class About extends React.Component{


render(){
return(
<div>
<h1>About Page !</h1>
</div>
)
}
}
export default About;
Home.js
import React from 'react';
import ReactDOM from 'react-dom';

class Home extends React.Component{


render(){
return(
<div>
<h1>Welcome to React Js Home Page</h1>
</div>
)
}
}
export default Home;
Contact.js
import React from 'react';
import ReactDOM from 'react-dom';

class Contact extends React.Component{


render(){
return(
<div>
<h1>Thank You for Contact Page</h1>
</div>
)
}
}
export default Contact;
NavLink Tag
import React from 'react';
import ReactDOM from 'react-dom';
import{BrowserRouter as Router,Route,Link,NavLink,Switch} from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';

const routing = (
<Router>
<div>
<h1> React Router Example </h1>
<ul>
<li>
<NavLink to="/" exact activestyle={{color:"red"}}>Home</NavLink>
</li>
<li>
<NavLink to="/" exact activestyle={{color:"red"}}>About</NavLink>
</li>
<li>
<NavLink to="/" exact activestyle={{color:"red"}}>Contact</NavLink>
</li>
</ul>
<Route path="/"component={Home}/>
<Route path="/abt"component={About}/>
<Route path="/con"component={Contact}/>
</div>
</Router>
)
ReactDOM.render(routing,document.getElementById('root'));
import React from 'react';
import ReactDOM from 'react-dom';
import{BrowserRouter as Router,Route,Link,NavLink,Switch} from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
import Notfound from './Notfound';
Switch Tag
const routing = (
<Router>
<div>
<h1> React Router Example </h1>
<ul>
<li>
<NavLink to="/" exact activestyle={{color:"red"}}>Home</NavLink>
</li>
<li>
<NavLink to="/" exact activestyle={{color:"red"}}>About</NavLink>
</li>
<li>
<NavLink to="/" exact activestyle={{color:"red"}}>Contact</NavLink>
</li>
</ul>
<Switch>
<Route path="/"component={Home}/>
<Route path="/abt"component={About}/>
<Route path="/con"component={Contact}/>
<Route component={Notfound}/>
</Switch>
</div>
</Router>
)
ReactDOM.render(routing,document.getElementById('root'));
React crud
import React, { useState } from 'react';

function Crud() {
const [usernames, setUsernames] = useState([]);
const [inputValue, setInputValue] = useState('');
const [editIndex, setEditIndex] = useState(null);

// Handle input change


const handleInputChange = (e) => {
setInputValue(e.target.value);
};

// Create a new username


const handleCreate = () => {
if (inputValue.trim() !== '') {
setUsernames([...usernames, inputValue]);
setInputValue('');
}
};
// Update an username
const handleUpdate = () => {
if (editIndex !== null && inputValue.trim() !== '') {
const updatedUsernames = usernames.map((username, index) =>
index === editIndex ? inputValue : username
);
setUsernames(updatedUsernames);
setInputValue('');
setEditIndex(null);
}
};

const handleDelete = (indexToDelete) => {


const filteredUsernames = usernames.filter((_, index) => index
!== indexToDelete);
setUsernames(filteredUsernames);
if (editIndex === indexToDelete) {
setInputValue('');
setEditIndex(null);
}
};

const handleEdit = (indexToEdit) => {


setInputValue(usernames[indexToEdit]);
setEditIndex(indexToEdit);
};
return (
<div style={{ padding: '20px' }}>
<h1>Username CRUD Application</h1>
<input
type="text"
value={inputValue}
onChange={handleInputChange}
placeholder="Enter username"
/>
<button onClick={handleCreate}
disabled={editIndex !== null}>
Create
</button>
<button onClick={handleUpdate}
disabled={editIndex === null}>
Update
</button>
<ul>
{usernames.map((username, index)
=> (
<li key={index}>
{username}
<button onClick={() =>
handleEdit(index)}>Edit</button>
<button onClick={() =>
handleDelete(index)}>Delete</button>
</li>
))}
</ul>
</div>
);
}

export default Crud;


1. Counter App
➔ Create a simple counter with Increment, Decrement, and Reset buttons.

2. Todo List App


➔ Build a Todo List where you can Add, Delete, and Mark tasks as completed.

3. Form Handling
➔ Create a form with inputs like Name, Email, and Message.
➔ On submit, display the data.

4. Login Form Validation


➔ Build a simple login page and validate Username and Password fields.
➔ Show error messages if fields are empty.

5. Conditional Rendering
➔ Show different messages depending on a user's login status (like "Welcome"
or "Please log in").
•Fetch API Data
➔ Fetch user data from an API (like
https://jsonplaceholder.typicode.com/users)
➔ Display it in a list.

•Image Gallery App


➔ Display a grid of images.
➔ Click on an image to show it bigger (like a modal view).

•React Router Basic Setup


➔ Create a multi-page app with Home, About, and Contact pages using
React Router.

•Props and State Together


➔ Create a Card component that receives data via props and
renders it.
➔ Change the card content using state.

•Dark Mode Toggle


➔ Add a button to switch the app between light and dark mode.
1.Create a simple counter with Increment, Decrement, and Reset
buttons.

import React, { useState } from "react";

function CounterApp() {
const [count, setCount] = useState(0);

const handleIncrement = () => {


setCount(count + 1);
};

const handleDecrement = () => {


setCount(count - 1);
};

const handleReset = () => {


setCount(0);
};
return (
<div style={{ textAlign: "center",
marginTop: "50px" }}>
<h1>Counter: {count}</h1>
<button onClick={handleIncrement}
style={{ margin: "5px" }}>
Increment
</button>
<button onClick={handleDecrement}
style={{ margin: "5px" }}>
Decrement
</button>
<button onClick={handleReset}
style={{ margin: "5px" }}>
Reset
</button>
</div>
);
}

export default CounterApp;


2.Build a Todo List where you can Add, Delete, and Mark tasks
as completed.

import React, { useState } from "react";

function TodoList() {
const [task, setTask] = useState("");
const [todos, setTodos] = useState([]);

const handleAddTask = () => {


if (task.trim() !== "") {
setTodos([...todos, { text: task, completed:
false }]);
setTask(""); // Clear input
}
};

const handleDeleteTask = (index) => {


const newTodos = todos.filter((_, i) => i !==
index);
setTodos(newTodos);
};
const handleToggleComplete = (index) => {
const newTodos = [...todos];
newTodos[index].completed = !
newTodos[index].completed;
setTodos(newTodos);
};

return (
<div style={{ textAlign: "center", marginTop: "50px"
}}>
<h1>Todo List</h1>
<input
type="text"
placeholder="Enter task..."
value={task}
onChange={(e) => setTask(e.target.value)}
style={{ padding: "10px", width: "200px",
marginRight: "10px" }}
/>
<button onClick={handleAddTask} style={{ padding:
"10px" }}>
Add Task
<ul style={{ listStyle: "none", padding: 0, marginTop:
"20px" }}>
{todos.map((todo, index) => (
<li
key={index}
style={{
textDecoration: todo.completed ? "line-
through" : "none",
marginBottom: "10px",
}}
>
{todo.text}
<button
onClick={() =>
handleToggleComplete(index)}
style={{ marginLeft: "10px" }}
>
{todo.completed ? "Undo" : "Complete"}
</button>
<button
onClick={() =>
handleDeleteTask(index)}
style={{ marginLeft: "10px", color:
"red" }}
>
Delete
</button>
</li>
))}
</ul>
</div>
);
}

export default TodoList;


Form Handling

3.Create a form with inputs like Name, Email, and Message.On submit,
display the data.

import React, { useState } from "react";

const SimpleForm = () => {


const [formData, setFormData] = useState({
name: "",
email: "",
message: ""
});

const [submittedData, setSubmittedData] = useState(null);

const handleChange = (e) => {


setFormData({
...formData,
[e.target.name]: e.target.value
});
};
const [submittedData,
setSubmittedData] =
useState(null);

const handleChange = (e) => {


setFormData({
...formData,
[e.target.name]:
e.target.value
});
};

const handleSubmit = (e) => {


e.preventDefault();
setSubmittedData(formData);
setFormData({ name: "",
email: "", message: "" }); //
Clear the form after submit
};
return (
<div style={{ padding:
"20px" }}>
<h2>Contact Form</h2>
<form
onSubmit={handleSubmit}>
<div>
<label>Name:
</label><br />
<input
type="text"
name="name"

value={formData.name}

onChange={handleChange}
required
/>
</div>
<br />
<div>
<label>Email:
</label><br />
<input
type="email"
name="email"

value={formData.email}

onChange={handleChange}
required
/>
</div>
<br />
<div>
<label>Message:
</label><br />
<textarea
name="message"

value={formData.message}

onChange={handleChange}
required
/>
</div>
<br />
<button
type="submit">Submit</button>
</form>
{submittedData && (
<div style={{ marginTop:
"20px" }}>
<h3>Submitted
Data:</h3>

<p><strong>Name:</strong>
{submittedData.name}</p>

<p><strong>Email:</strong>
{submittedData.email}</p>

<p><strong>Message:</strong>
{submittedData.message}</p>
</div>
)}
</div>
);
};

export default SimpleForm;


4. Login Form Validation

➔ Build a simple login page and validate Username and Password fields.
➔ Show error messages if fields are empty.

import React, { useState } from "react";

const LoginPage = () => {


const [formData, setFormData] = useState({ username: "",
password: "" });
const [errors, setErrors] = useState({});

const handleChange = (e) => {


setFormData({
...formData,
[e.target.name]: e.target.value
});
};
const handleSubmit = (e) => {
e.preventDefault();
const validationErrors = {};

if (!formData.username.trim()) {
validationErrors.username = "Username is required.";
}
if (!formData.password.trim()) {
validationErrors.password = "Password is required.";
}

setErrors(validationErrors);

if (Object.keys(validationErrors).length === 0) {
alert("Login Successful!");
// You can redirect or clear the form here
}
};
return (
<div style={{ padding: "20px" }}>
<h2>Login Page</h2>
<form onSubmit={handleSubmit}>
<div>
<label>Username:</label><br />
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
/>
{errors.username && <p style={{ color:
"red" }}>{errors.username}</p>}
</div>
<br />
<div>
<label>Password:</label><br/>
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}/>
{errors.password && <p
style={{ color:
"red" }}>{errors.password}</p>}
</div>
<br />
<button type="submit">Login</button>
</form>
</div>
);
};

export default LoginPage;


5.Conditional Rendering

➔ Show different messages depending on a user's login status (like


"Welcome" or "Please log in").

import React, { useState } from "react";

const LoginStatus = () => {


const [isLoggedIn, setIsLoggedIn] = useState(false);

const handleLogin = () => {


setIsLoggedIn(true);
};

const handleLogout = () => {


setIsLoggedIn(false);
};
return (
<div style={{ padding:
"20px" }}>
<h1>{isLoggedIn ?
"Welcome!" : "Please log
in."}</h1>
{isLoggedIn ? (
<button
onClick={handleLogout}>Logout</b
utton>
) : (
<button
onClick={handleLogin}>Login</but
ton>
)}
</div>
);
};

export default LoginStatus;

You might also like