Sheeba React Js {Updated}
Sheeba React Js {Updated}
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.
5) React Support Unit Testing Only 5) Angular Support Unit & Integration Testing
• 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.
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...
}
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();
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.
▫ 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';
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 <>
▫this.props.propName;
Props Example
</>
)}
}
export default Myweb
App.js - <Myweb
topic={"helooo"} />
import React from 'react';
function Myweb(props){
return(
<>
<h1> welcome to react
props {props.sheeba}</h1>
</>
)
}
<Myweb sheeba={"sheeba"}/>
Multi Props Example
}
}
</>
)}
}
export default Myweb
function Myweb(props){
return(
<>
<h1> welcome to react
props {props.name}{props.age}
{props.value}</h1>
</>
)
}
<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>
}
}
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
•
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";
function Myweb() {
const [initalvalue] = useState("Welcome");
return <h1>{initalvalue}</h1>;
}
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 [initialValue]
="Welcome";
const [name]="sheeba";
return (
<div>
<h1>{initialValue},{name}</h1>
</div>
);
};
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 [initialValue,
setInitialValue] =
useState("Welcome to");
const [name] = useState("
React State");
render() {
return <h1>{this.state.message}</h1>;
}
}
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
function MyComponent() {
const [message, setMessage] = useState('Hello,
React!');
return (
<div>
<h1>{message}</h1>
<button onClick={updateMessage}>Update
Message</button>
</div>
);
}
export default MyComponent
React List
return <li>{listvalues}</li>
});
ReactDOM.render(<ul>{rl}</ul>,document.getElementById('root'));
function NumberList() {
const newlist = [10, 20, 30, 40, 50];
return (
<div>
<h3>Number List:</h3>
<ul>{rl}</ul>
</div>
);
}
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.
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>
);
}
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>
);
}
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>
);
}
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())
useEffect(() => {
// This runs once like componentWillMount (but
safely after render)
alert('Learn ReactJS Lifecycle in Pumo Tech');
}, []);
return (
<h1>{state.value} {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>
);
}
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';
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';
• 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.
• View − The view will receive data from the store and re -
render the app.
Redux Architecture
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.
// 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
• Sass have lot of features that do not exist in CSS, like variables, nested rules, imports,
• Install Sass in your React App by running this command in your terminal
$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
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 HTML elements like input tag, the value of the input field
is changed whenever the user type.
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';
)
}
}
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.
Rules of Hooks :
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
• 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>
<Navbar/>
<h1> hai i am home page</h1>
</>
)
}
About.js
</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';
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);
3. Form Handling
➔ Create a form with inputs like Name, Email, and Message.
➔ On submit, display the data.
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.
function CounterApp() {
const [count, setCount] = useState(0);
function TodoList() {
const [task, setTask] = useState("");
const [todos, setTodos] = useState([]);
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>
);
}
3.Create a form with inputs like Name, Email, and Message.On submit,
display the data.
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>
);
};
➔ Build a simple login page and validate Username and Password fields.
➔ Show error messages if fields are empty.
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>
);
};