React Js Notes by Tishant Agrawal
React Js Notes by Tishant Agrawal
https://react.dev
)
If node.js was completely installed on your system, the command
prompt will print the version of the node.js installed.
create folder
react_learn
open is vs code
npm install
then select folder - open terminal - npx create-react-app demo
(folder name)
Note :
react used virtual DOM because update only required list .
DOM complete list update.
used app
Youtube
whatsapp
netflix
react bootstrap
npm i react-bootstrap
react-router-dom
npm i react-router-dom
Components
Example
header
footer
create folder : pages
header.jsx
footer.jsx
services.jsx
carrier.jsx
class component
function component
render Method
The render() method is then called to define the React
component that should be rendered.
user.jsx
call in App.js
import './App.css';
import User from './Pages/Users';
function App() {
return (
<div className="App">
<User/>
</div>
);
}
User.jsx
function User()
{
function Apple()
{
alert("function called");
}
return(
<>
<div>
<button onClick={Apple()}>Click Me</button>
</div>
</>
)
}
export default User
function User()
{
function Apple()
{
alert("function called");
}
return(
<>
<div>
// <button onClick={Apple}>Click Me</button>
// using arrow ()
<button onClick={()=>alert("hellooo")}>Click me</button>
</div>
</>
)
}
export default User
React-router-dom
React Router Dom has many useful components and to create fully
functioning routing, you need most of these.
routing functionality .
the component associated with that exact path. All routes are
routes.
install react-router-dom
npm i react-router-dom
install bootstrap
pages create
Home
About us
Contact Us
Services
Home.jsx
App.js
import './App.css';
import React from 'react';
import {BrowserRouter , Routes,Route} from "react-router-dom";
import About from './pages/About';
import Contact from './pages/Contact';
import Header from './pages/Header';
import Home from './pages/Home';
import Services from './pages/Services';
function App() {
return (
<>
<BrowserRouter>
<Routes>
<Route path="/" element={<Home/>}></Route>
<Route path="/About" element={<About/>}></Route>
<Route path="/Contact" element={<Contact/>}></Route>
<Route path="/Services" element={<Services/>}></Route>
</Routes>
</BrowserRouter>
{/* <Header/>
<Home/>
<About/>
<Contact/>
<Services/> */}
</>
);
}
export default App;
React Keys
Lists are used to display data in an ordered format and mainly used to
display menus on websites.
map():
The map() method creates a new array with the results of calling a
function for every array element.
The map() function is used for traversing the lists and updates elements
to be enclosed between <li> </li> elements.
for example
<html>
<body>
<script>
var arr=[2.1,3.5,4.7];
var result=arr.map(Math.round);
document.writeln(result);
</script>
</body>
</html>
<html>
<body>
<script>
var arr=[2,4,6];
var result=arr.map(x=>x*3);
document.writeln(result);
</script>
</body>
</html>
map()
<script>
const numbers = [1, 2, 3, 4, 5];
const num = numbers.map((number) => number * 2);
document.write(num);
</script>
JSON
“Age” : 30,
“City” : “Bundi” ,
“Country” : “India”
Dynamic Header
import React from 'react';
import { Link } from 'react-router-dom';
import Dhead from './Header';
<li key={items.id}>
<Link to={items.path}>{items.title}</Link>
</li>
</>
)
})
}
{/* <a href="/">Home</a>
<a href="">About Us</a>
<a href="">Contact Us</a>
<a href="">Service</a> */}
<ul>
{/* <li><Link to="/About">About Us</Link></li>
<li><Link to="/Contact">Contact Us</Link></li>
<li><Link to="/Services">Services</Link></li> */}
</ul>
</>
)
}
Table.jsx
Example 2
import React from 'react'
)
}
index.css
table {
width: 800px;
height: 200px;
border-collapse: collapse;
}
th {
border-bottom: 1px solid black;
border: 2px solid black;
}
td {
text-align: center;
border: 2px solid black;
}
Form in react
Form.jsx
return (
<>
<div className="App">
<h1>Form in React</h1>
<fieldset>
<form>
required />
<input
type="text"
name="lastname"
id="lastname"
required
/>
<input
type="email"
name="email"
id="email"
placeholder="Enter email"
required
/>
<label for="tel">Contact*</label>
<input
type="tel"
name="tel"
id="tel"
required
/>
<label for="gender">Gender*</label>
<br />
Female
Other
<br />
English
id="maths" />
Maths
id="physics" />
Physics
<input
type="file"
name="file"
id="file"
required
/>
<input
type="url"
name="url"
id="url"
placeholder="Enter url"
required
/>
</option>
<optgroup label="Beginers">
<option value="1">HTML</option>
<option value="2">CSS</option>
<option value="3">JavaScript</option>
</optgroup>
<optgroup label="Advance">
<option value="1">React</option>
<option value="2">Node</option>
<option value="3">Express</option>
<option value="4">MongoDB</option>
</optgroup>
</select>
<label for="about">About</label>
<br />
<textarea
name="about"
id="about"
cols="30"
rows="10"
required
></textarea>
<label>Submit OR Reset</label>
<br />
Reset
</button>
<button type="submit" value="Submit">
Submit
</button>
</form>
</fieldset>
</div>
</>
index.css
Form css
body {
background-color: azure;
color:#fff;
h1 {
text-align: center;
color: black;
fieldset {
margin-left: 20%;
margin-right: 20%;
input {
padding: .3rem;
border-radius: 4px;
margin: 10px;
label {
margin: 10px;
button {
padding: .3rem;
font-size: 15px;
color: #ccc;
padding: 10px;
border-radius: 8px;
margin: 10px;
cursor: pointer;
}
Types of components in ReactJS
1.Class component
2.functional Component
Example
function demoComponent() {
return (
<h1>
Welcome Message!
</h1>);
}
Example
React lifecycle methods (for example, React lifecycle methods can be used inside
componentDidMount) cannot be used in class components (for example,
functional components. componentDidMount).
It requires different syntax inside a class
component to implement hooks.
constructor(props) {
Example:
super(props);
const [name,SetName]=
React.useState(' ')
this.state = {name: ' '}
render() {
return (
<>
<h1>helllooo world</h1>
</>
)
}
React Hooks
Rules of Hooks
Hooks State
Hook state is the new way of declaring a state in React app. Hook uses
useState() functional component for setting and retrieving state
Built-in Hooks
Basic Hooks
○ useState
○ useEffect
○ useContext
Additional Hooks
○ useReducer
○ useCallback
○ useMemo
○ useRef
state The state is a built-in React object that is used to contain data or
information about the component. A component's state can change over
time; whenever it changes, the component re-renders.
About.jsx
const[data,setdata]=useState("varsha")
//const[data,setdata]=useState("")
const Update=()=>{
return (
<>
<div className="App">
<h1>{data}</h1>
</div>
</>
const[count,setCount]=useState(0);
const inc=()=>{
setCount(count+1);
}
const dec=()=>{
setCount(count-1);
return (
<>
<div>
<h1> {count}</h1>
<button onClick={inc}>+</button>
</div>
</>
function Counter() {
<>
>Update Color</button>
</>
function Counter() {
return (
<>
<div>
</div>
</>
);
Note The state is a built-in React object that is used to contain data
Form.jsx
function Form() {
username: '',
password: ''
});
username: '',
password: ''
});
e.preventDefault();
setForm({
username: data.username,
password: data.password
});
submitted(true);
};
setData({
...data,
[e.target.name]: e.target.value
});
};
return (
<div>
<form onSubmit={printValues}>
<label> Username: <input value={data.username}
name="username"onChange={updateField}
/>
</label>
<br />
/>
</label>
<br />
<button>Submit</button>
</form>
</div>
);
function increment() {
return (
<div>
<br />
<button onClick={increment}>
</button>
</div>
);
Form.jsx
function Form() {
const [username, setUsername] = useState('');
e.preventDefault();
console.log(username, password);
};
return (
<form onSubmit={printValues}>
<label>
Username:
</label>
<br />
<label>
Password:
<br />
<button>Submit</button>
</form>
);
preventDefault
Contact.jsx
function Contact() {
console.log(data);
return (
<>
<form onSubmit={handleSubmit(onSubmit)}>
</form>
</>
);
function Contact() {
setSelectedFile(file);
};
else
};
return (
<div>
{selectedFile!=null && (
<div>
<img src={URL.createObjectURL(selectedFile)}
)}
</div>
);
constructor()
super();
this.state={
data:"hellllo World"
apple()
{
// alert ("fruit")
this.setState({data:"Rajasthan"})
render()
return(
<>
<h1>{this.state.data}</h1>
</>
);
use react-hook-form
<form onSubmit={handleSubmit(onSubmit)}>
// input field 1
// input field 2
</form>
Contact.jsx
function Contact() {
return (
<>
</>
);
function Counter() {
return (
<>
<div>
</div>
</>
);
setMessage(e.target.value);
};
setUpdated(message);
};
return (
<div>
<h2>Message: {message}</h2>
</div>
);
}
Image upload
createObjectURL() method
Syntax:
const url = URL.createObjectURL(object);
function Contact() {
setSelectedFile(file);
};
if (selectedFile)
else
};
return (
<div>
{selectedFile!=null && (
<div>
<img
</div>
)}
</div>
);
Example
import React, { useState } from "react";
import 'react-toastify/dist/ReactToastify.css';
const emailchange=(e)=>
{ setemail(e.target.value)
if(email=="")
else if (email=="[email protected]")
alert("Hello Varsha"); }
else{
}
return(
<>
<ToastContainer/>
<form>
</form>
</>
export {Login}
const handleupclick=()=>
//console.log("uppercaser here");
const handlelwclick=()=>
settext(newtext)
const handlegap=()=>
settext(newtext)
const handleclr=()=>
settext(newtext)
const upperonchange=(e)=>
settext(e.target.value);
return (
<>
<h1>Analyze Example </h1>
<div className="mb-3">
<br/>
</div>
<p>{text.length}</p>
</>
props
Props stand for "Properties." They are read-only components. It is an object
which stores the value of attributes of a tag and work similar to the HTML
attributes. It gives a way to pass data from one component to other
components. It is similar to function arguments. Props are passed to the
component in the same way as arguments passed in a function.
Props are immutable so we cannot modify the props from inside the
component. Inside the components, we can add attributes called props.
These attributes are available in the component as this.props and can be
used to render dynamic data in our render method.
Table in react
import React from 'react';
function Tabledata() {
return (
<div className="App">
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
<tr>
<td>Anom</td>
<td>19</td>
<td>Male</td>
</tr>
<tr>
<td>Megha</td>
<td>19</td>
<td>Female</td>
</tr>
<tr>
<td>Subham</td>
<td>25</td>
<td>Male</td>
</tr>
</table>
</div>
);
React-Toastify
install
npm i react-toastify
import link
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
Toast Notifications are popup messages that are added so as to
display a message to a user. It can be a success message, warning
message, or custom message. Toast Notification is also called
Toastify Notifications.
function Showname(){
const notify = () => toast("Wow so easy!");
return (
<>
<div>
<button onClick={notify}>Notify!</button>
<ToastContainer />
</div>
</>
);
}
export default Showname;
toast example
Showname.jsx
function Showname(){
const notify = ()=>{
toast.warning('Danger')
toast.success('successful')
toast.info('Independence Day')
toast.error('Runtime error')
toast('Hello students')
}
return (
<div className="GeeksforGeeks">
<button onClick={notify}>Click Me!</button>
<ToastContainer />
</div>
);
}
export default Showname
Hooks
useEffect()
useRef()
useContext()
useState()
useNavigate()
useLocation()
useMemo()
useReducer()
useCallback()
custom hooks()
useEffect Hooks
The useEffect Hook allows you to perform side effects in your
components.
side effects are: fetching data, directly updating the DOM ,manually
changing the DOM in React components.
The useEffect hook in React is use to handle the side effects in React
such as fetching data, and updating DOM. This hook runs on every
render but there is also a way of using a dependency array using which
we can control the effect of rendering .
Syntax
useEffect(()=>{},[]);
without dependency
useEffect(<function>, <dependency>)
useEffect(() => {
});
with dependency
useEffect(()->{
// Code
}, [] )
function Counteffect() {
useEffect(() => {
setTimeout(() => {
}, 1000);
});
return (
<div>
Click me
</button> */}
<button>click me</button>
</div>
);
Useeffect Example
function Counteffect() {
useEffect(() => {
}, [count]);
return (
<>
<p>Count: {count}</p>
</>
);
useEffect Example
useEffect(() => {
}, [count]);
return (
<>
<div>
</button>
</div>
</>
usecontext
React Context is a way to manage state globally.
Benefit
React useContext hook allows sharing data across a React component tree
without passing props down through multiple levels.
Create Context
const UserContext = createContext()
Context Provider
Wrap child components in the Context Provider and supply the state
value.
import
function Component1() {
return (
<UserContext.Provider value={user}>
<h1>{`Hello ${user}!`}</h1>
<Component2 />
</UserContext.Provider>
);
function Component2() {
return (
<>
<h1>Component 2</h1>
<Component3 />
</>
);
function Component3() {
return (
<>
<h1>Component 3</h1>
<Component4 />
</>
);
function Component4() {
return (
<>
<h1>Component 4</h1>
<Component5 />
</>
);
function Component5() {
return (
<>
<h1>Component 5</h1>
</>
);
}
export default Component1;
note:
redux is same as Context API
Parent.jsx
import React, { createContext,useState } from 'react';
import Child from './Child';
import Superchild from './Superchild';
function Parent() {
const[color,setcolor]= useState('green');
return (
<>
<GlobalInfo.Provider value={{parentColor:color}}>
<div>
<h1>AppParent Component </h1>
<Child />
<Superchild/>
</div>
</GlobalInfo.Provider>
</>
)
}
export default Parent;
Child.jsx
)
}
Superchild.jsx
)
}
useMemo
(unwanted stop function calling)
useMemo
import React, { useState, useMemo } from "react";
function multiCount()
{
console.warn("multiCount");
return count*5;
}
return (
<>
<div>
<h1>UseMemo hook used with example</h1>
<h2>Count :{count}</h2>
<h2>Item :{item}</h2>
<h2>{multiCount()}</h2>
{/* <h2>{multiCountMemo}</h2> */}
useRef Hook
The useRef is a hook that allows to directly create a reference to the
DOM element in the functional component.The useRef hook is a new
addition in React 16.8.
useRefis a React Hook that reference a value that’s not needed
for rendering.
syntax
const ref = useRef(initialValue)
The useRef Hook allows you to persist values between renders. It can be
used to store a mutable value that does not cause a re-render when updated.
It can be used to access a DOM element directly.
// function Exref() {
// <br/><br/>
// <textarea ref={focusPoint}/>
// </>
// );
// };
// useEffect(()=>{
// setcount(count+1)
// count.current = count.current + 1;
// });
// },[]);
// const chnge=(e)=>{
// setmydata (e.target.value);
// }
// return(
// <>
// <input type="text" value={mydata} onChange={chnge}/>
// <h3>Total number of count render is {count.current}</h3>
// </>
// )
// }
// export default Exref;
// const[mydata,setmydata]=useState("");
// const changeStyle=()=>{
// inputElem.current.style.backgroundColor ="red";
// inputElem.current.focus();
// }
// const chnge=(e)=>{
// setmydata (e.target.value);
// }
// return(
// <>
// <input ref={inputElem} type="text" value={mydata}
onChange={chnge}/>
// <br/>
// <button onClick={changeStyle}>Submit</button>
// </>
// )
// }
// export default Exref;
// useEffect(() => {
// console.log(inputRef.current);
// inputRef.current.focus();
// }, []);
// return (
// <>
// return <input ref={inputRef} type="text" />
// </>
// )
// }
// useEffect(() => {
// return () => clearInterval(timerIdRef.current);
// }, []);
// return (
// <>
// <div>
// <h1>Timer: {count}s</h1>
// <div>
// <button onClick={startHandler}>Start</button>
// <button onClick={stopHandler}>Stop</button>
// </div>
// </div>
// </> )
// }
return (
<div>
<button onClick={handle}>Click me</button>;
</div>
)
}
function Back()
{
const[add,setadd]=useState(0);
const[count,setcount]=useState(0);
},[count])
</>
)
}
export default Back;
without callback ()
// funccount.add(incrementCounter);
// funccount.add(decrementCounter);
// funccount.add(incrementNumber);
// alert(funccount.size);
// return (
// <>
// <div>Count: {count}
// <button onClick={incrementCounter}>Increase counter</button>
// <button onClick={decrementCounter}>Decrease Counter</button>
// <button onClick={incrementNumber}>increase number</button>
// </div>
// </>
// )
// }
// with callback()
import React, { useState, useCallback } from 'react'
var funccount = new Set();
const Back = () => {
funccount.add(incrementCounter);
funccount.add(decrementCounter);
funccount.add(incrementNumber);
alert(funccount.size);
return (
<>
<div>Count: {count}
<br/><br/>
<button onClick={incrementCounter}>Increase counter</button>
<button onClick={decrementCounter}>Decrease Counter</button>
<button onClick={incrementNumber}>increase number</button>
</div>
</>
)
}
export default Back;
uesReducer Hook
useReducer Hook is similar to the useState Hook.
useReducer(<reducer>, <initialState>)
The reducer function contains your custom state logic and the
initialStatecan be a simple value but generally will contain an
object.
import reducer
Syntax
The useReducer hook takes three arguments including reducer, initial
state, and the function to load the initial state.
import React, { useReducer } from "react";
// const initialState=0;
// switch(action)
// {
// case "Increment" :
// return state+1
// case "Decrement" :
// return state-1
// default:
// return state
// }
// }
// function Recounter()
// {
// useReducer(reducer , initialState)
// return(
// <>
// <div>
// <h1>count={count}</h1>
// <button onClick={()=>dispatch("Increment")}>
Increment</button>
// <button
onClick={()=>dispatch("Decrement")}>Decrement</button>
// </div>
// </>
// )
// }
// switch (action.type) {
// case 'increment':
// case 'decrement':
// default:
// }
// }
// function Recounter() {
// return (
// <>
// Count: {state.count}
// <br/>
// );
// }
const initialState = 0;
switch (action) {
case "add":
return state + 1;
case "subtract":
return state - 1;
case "reset":
return 0;
default:
};
return (
<div>
<h2>{count}</h2>
</div>
);
};
useNavigte hook()
useNavigation is a Hook available in React Router.
The useNavigate() hook is introduced in the React Router v6 to replace
the useHistory() hook.
pages:
(services , tabledata, counter,demonav)
Services.jsx
import React, { useEffect, useState } from "react";
function Services(){
const[name,setname]=useState("");
const[text,settext]=useState("");
const click=()=>{
//settext("hello");
newnav("/Counter",{state:{text:text}});
const chnge=(e)=>{
setname(e.target.value);
useEffect(()=>{
settext(name);
})
return(
<>
<label>Name:</label>
</>
Tabledata.jsx
import React from 'react';
function Tabledata() {
return (
<div className="App">
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
<tr>
<td>Anom</td>
<td>19</td>
<td>Male</td>
</tr>
<tr>
<td>Megha</td>
<td>19</td>
<td>Female</td>
</tr>
<tr>
<td>Subham</td>
<td>25</td>
<td>Male</td>
</tr>
</table>
</div>
);
Demonav.jsx
import React from 'react';
function Demonav() {
return (
<>
<div>
</div>
</>
Counter.jsx
import React from "react";
function Counter() {
<>
<div>
</div>
</>
);
install mdb-react-ui-kit
npm i mdb-react-ui-kit
import 'react-toastify/dist/ReactToastify.css';
import {
MDBBtn,
MDBContainer,
MDBRow,
MDBCol,
MDBCard,
MDBCardBody,
MDBInput,
MDBIcon,
MDBCheckbox
from 'mdb-react-ui-kit';
function Login() {
const navigatee=useNavigate();
const namechange=(e)=>
setname(e.target.value)
const passchange=(e)=>
setpass(e.target.value)
const numberchange=(e)=>
setnumber(e.target.value)
const emailchange=(e)=>
{
setemail(e.target.value)
if (name=="")
else if(!isNaN==name)
else if (pass=="")
else if(email=="")
{
alert("Please fill your Email");
else if(number=="")
else
toast.success("congratulations..........");
setTimeout(() => {
navigatee("/Textform")
}, 3000);
return(
<>
<ToastContainer/>
<MDBContainer fluid>
<MDBCol col='12'>
Login
</MDBBtn>
<span class="forget">
</span>
<hr/>
</MDBCardBody>
</MDBCard>
</MDBCol>
</MDBRow>
</MDBContainer>
</>
);
props:
React allows us to pass information to a Component using
something called props (which stands for properties). Props are
objects which can be used inside a component.
Props are immutable so we cannot modify the props from inside the
component. Inside the components, we can add attributes called props.
parse() function
The parse() function takes the argument of the JSON source and
converts it to the JSON format.
because most of the time when you fetch the data from the server the
format of the response is the string
API
API stands for Application Programming Interface. It is a medium
that allows different applications to communicate programmatically
with one another and return a response.
React utilizes API calls to connect with external services to receive or send
data. They allow React application to interact with other systems and
exchange information with them.
The await keyword is used inside the async function to wait for
the asynchronous operation.
Async functions always return a promise.
The keyword 'async' before a function makes the function return a promise,
always. And the keyword await is used inside async functions, which makes
the program wait until the Promise resolves.
api url
fakestoreapi.com/products
https://jsonplaceholder.typicode.com/users
Apirender.jsx
import Button from 'react-bootstrap/Button';
function Apirender() {
// const getapi=async()=>{
// // console.log(result);
// setcard(await result.json());
// }
// useEffect(()=>{
// getapi();
// },[])
return (
<div className='flex-card'>
Dcrd.map((items=>{
return(
<>
<Card>
<Card.Body>
<Card.Title>{items.title}</Card.Title>
<Card.Text>
{items.text}
</Card.Text>
<h5>{items.price}</h5>
</Card.Body>
</Card>
</div>
</>
}))
</div>
);
Dcrd.jsx
const Dcrd=[
id:1,
// img:`${myimage}`,
url:"/Card",
title:"Nature Image",
},
id:2,
url:"/Card",
// img:`${myimage}`,
title:"Water Image",
},
id:3,
url:"/Card",
title:"Mountain Image",
// img:"img1.jpg",
},
id:4,
img:"",
title:"Mountain Image",
url:"/Card",
// img:"img1.jpg",
},
id:5,
img:"",
title:"Mountain Image",
url:"/Card",
// img:"img1.jpg",
update:"Last updated 3 mins ago",
},
id:6,
img:"",
title:"Mountain Image",
url:"/Card",
// img:"img1.jpg",
},
id:7,
img:"",
title:"Mountain Image",
url:"/Card",
// img:"img1.jpg",
},
id:8,
img:"",
title:"Mountain Image",
url:"/Card",
img:"img1.jpg",
},
id:9,
img:"",
title:"Mountain Image",
url:"/Card",
img:"img1.jpg",
// function Apirender() {
// const[Datacard,setcard]=useState([]);
// const getapi=async()=>{
// // console.log(result);
// setcard(await result.json());
// }
// useEffect(()=>{
// getapi();
// },[])
// return (
// <div className='flex-card'>
// {
// Dcrd.map((items=>{
// return(
// <>
// <Card>
// <Card.Body>
// <Card.Title>{items.title}</Card.Title>
// <Card.Text>
// {items.text}
// </Card.Text>
// <h5>{items.price}</h5>
// </Card.Body>
// </Card>
// </div>
// </>
// )
// }))
// }
// </div>
// );
// }
// fetch("https://jsonplaceholder.typicode.com/users")
// .then(response => {
// return response.json()
// })
// .then(data => {
// setUsers(data)
// })
// }
// useEffect(() => {
// fetchUserData()
// }, [])
// return (
// <div>
// <ul>
// {users.map(user => (
// <h1><li key={user.id}>{user.name}</li></h1>
// ))}
// {users.map(user => (
// <li key={user.id}>{user.username}</li>
// ))}
// </ul>
// )}
// </div>
// );
// }
return fetch(url)
useEffect(() => {
fetchInfo();
}, []);
return (
<div className="App">
<center>
return (
<div
style={{
width: "15em",
backgroundColor: "#35D841",
padding: 2,
borderRadius: 10,
marginBlock: 10,
}}
>
</div>
);
})}
</center>
</div>
);
Custom Hooks
Custom React hooks are an essential tool that let you add special,
unique functionality to your React applications.
codebase.
change it once.
hook and therefore can’t apply the rules of hooks to it. So, you
Cnthk.jsx
import React from 'react';
import { useState , useEffect } from 'react';
function Cnthk() {
const[counter,setcounter]=useState(0)
useTitle(counter)
// useEffect(()=>{
// document.title=counter+"hits on button"
// })
return (
<>
<div>
<h1>{counter}</h1>
</div>
</>
function useTitle(counter) {
useEffect(()=>{
document.title=counter+"hits on button"
})
15 Useful React Custom Hooks That You Can Use In Any Project -
DEV Community
How to Build Your Own React Hooks: A Step-by-Step Guide
(freecodecamp.org)
Controlled Component
A controlled component is bound to a value, and its changes will be handled in
code by using event-based callbacks. Here, the input form element is handled
by the react itself rather than the DOM. In this, the mutable state is kept in the
state property and will be updated only with setState() method.
Controlled components have functions that govern the data passing into them
on every onChange event occurs. This data is then saved to state and updated
with setState() method. It makes component have better control over the form
elements and data.
Uncontrolled Component
It is similar to the traditional HTML form inputs. Here, the form data is handled
by the DOM itself. It maintains their own state and will be updated when the
input value changes. To write an uncontrolled component, there is no need to
write an event handler for every state update, and you can use a ref to access
the value of the form from the DOM.
no controlled uncontrolled
state.
prop. values.
control.
5. It has better control over the It has limited control over the
React Redux
Redux is an open-source JavaScript library used to manage application state.
React uses Redux for building the user interface. It was first introduced by Dan
Abramov and Andrew Clark in 2015.
React Redux is the official React binding for Redux. It allows React
components to read data from a Redux Store, and dispatch Actions to the
Store to update data. Redux helps apps to scale by providing a sensible way to
manage state through a unidirectional data flow model. React Redux is
conceptually simple. It subscribes to the Redux store, checks to see if the data
which your component wants have changed, and re-renders your component.
React Redux is the official UI bindings for React applications that provides a
predictable and centralized way to manage the state of your application.
STORE: A Store is a place where the entire state of your application lists. It
manages the status of the application and has a dispatch(action) function. It
is like a brain responsible for all moving parts in Redux.
ACTION: Action is sent or dispatched from the view which are payloads that
can be read by Reducers. It is a pure object created to store the information of
the user's event. It includes information such as type of action, time of
occurrence, location of occurrence, its coordinates, and which state it aims to
change.
REDUCER: Reducer read the payloads from the actions and then updates the
store via the state accordingly. It is a pure function to return a new state from
the initial state.
cd learn
npm start
install redux
Syntax:
event.preventDefault()
state()
A state in Redux is a JavaScript object, where the internal state of the
application is stored.
redux project
open AddTodo.jsx
<Row>
<Col md={12}>
<Card className='shadow-sm'>
<Card.Body>
<DisplayCount />
<Form onSubmit={handleSubmit}>
<Form.Group>
<Form.Label>Todo Title</Form.Label>
<Form.Control type='text'
placeholder='Enter here todo'
value={todo.title}
onChange={event=>setTodo({...todo,title:event.target.value})}></Form.Co
ntrol>
</Form.Group>
<Form.Group className='mt-3'>
<Form.Label>Todo
Description</Form.Label>
<Form.Control as={'textarea'}
type='text'
value={todo.description}
onChange={event=>setTodo({...todo,description:event.target.value})}
></Form.Control>
</Form.Group>
<Container>
<Button type='submit'
variant='primary'>
Add Todo
</Button>
</Container>
</Form>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
title:'',
description:'',
id:''
})
event.preventDefault()
console.log(todo)
setTodo({
title:'',
description:''
})
DisplayTodos.jsx
return (
<Container>
<Row>
<Col>
<Card.Body>
<DisplayCount />
<ListGroup>
todos.map((todo,index)=>(
<ListGroup.Item key={index}>
<h4>{todo.title}</h4>
<p>{todo.description}</p>
<Button
onClick={event=>deleteTodo(todo.id)} variant='danger' size="sm">
Delete
</Button>
</ListGroup.Item>
))
</ListGroup>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
create useState
function DisplayTodos() {
const[todos,setTodos]=useState([
title:'First Name',
description:'First desc'
},
title:'Second Name',
description:'Second desc'
}
]);
<Card.Body>
<DisplayCount />
<ListGroup>
todos.map((todo,index)=>(
<ListGroup.Item key={index}>
<h4>{todo.title}</h4>
<p>{todo.description}</p>
</ListGroup.Item>
))
</ListGroup>
</Card.Body>
open DisplatCount.jsx
import React from 'react'
return (
<Card.Body>
</Card.Body>
</Card>
)
1. action-types.js
2. todo.js
3. user.js
actions-type.js file
create constant type for action (add , update ,delete)
action-types.js
export const ADD_TODO="ADD_TODO"
todo.js
import { ADD_TODO, DELETE_TODO, UPDATE_TODO } from
"./action-types";
//add todo
type:ADD_TODO,
payload:todo
})
//delete todo
type:DELETE_TODO,
payload:id
})
//update todo
type:UPDATE_TODO,
payload:{todo:todo,todoId:id}
})
const initialState=[]
switch(action.type)
case ADD_TODO:
//add todo
//delete todo
const newState
=state.filter((todo)=>todo.id!==action.payload)
return newState
case UPDATE_TODO:
//update todo
state.map(todo=>{
if(todo.id==action.payload.todoId)
todo.title=action.payload.todo.title
todo.description=action.payload.todo.description
return todo
})
// return updateState
default:
return state
// if(action.type===ADD_TODO)
// {
// }
// else if(action.type===DELETE_TODO)
// {
// }
// else if(action.type===UPDATE_TODO)
// {
// }
// else
// {
// }
App.js
used provider
(provider - react redux)
provider - sare store ko hierarchy m lega .
store used in all component
return (
<Provider store={store}>
<Container className='py-3'>
<AddTodo />
<DisplayTodos />
</Container>
</Provider>
);
function App() {
return (
<Provider store={store}>
<Container className='py-3'>
<AddTodo />
<DisplayTodos />
</Container>
</Provider>
);
}
export default App;
In Add todo:
const AddTodo = ({addTodo}) => {
addTodo pass
addtodo call
const handleSubmit=(event)=>{
event.preventDefault()
// console.log(todo)
setTodo({
title:'',
description:''
})
const mapDispatchToProps=(dispatch)=>({
addTodo:(todo)=>(dispatch(addTodo(todo)))
})
const[todo,setTodo]=useState(
title:'',
description:'',
id:''
})
const handleSubmit=(event)=>{
event.preventDefault()
addTodo({...todo,id:v4()})
// console.log(todo)
setTodo({
title:'',
description:''
})
return (
<Container>
<Row>
<Col md={12}>
<Card className='shadow-sm'>
<Card.Body>
<DisplayCount />
<Form onSubmit={handleSubmit}>
<Form.Group>
<Form.Label>Todo
Title</Form.Label>
<Form.Control type='text'
placeholder='Enter here todo'
value={todo.title}
onChange={event=>setTodo({...todo,title:event.target.value})}></F
orm.Control>
</Form.Group>
<Form.Group className='mt-3'>
<Form.Label>Todo
Description</Form.Label>
<Form.Control as={'textarea'}
type='text'
placeholder='Enter here
Description'
value={todo.description}
onChange={event=>setTodo({...todo,description:event.target.value}
)}
></Form.Control>
</Form.Group>
<Container>
<Button type='submit'
variant='primary'>
Add Todo
</Button>
</Container>
</Form>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
const mapStateToProps=(state)=>({})
const mapDispatchToProps=(dispatch)=>({
addTodo:(todo)=>(dispatch(addTodo(todo)))
})
export default
connect(mapStateToProps,mapDispatchToProps)(AddTodo)
DisplayTodos.jsx
const mapStateToProps=(state)=>{
//console.log(state.todoReducer)
return{todos:state.todoReducer}
const mapDispatchToProps=(dispatch)=>({})
then connect()
export default
connect(mapStateToProps,mapDispatchToProps)(DisplayTodos)
DisplayTodos.jsx
import React, { useState } from 'react'
function DisplayTodos({todos,deleteTodo}) {
// const[todos,setTodos]=useState([
// {
// title:'First Name',
// description:'First desc'
// },
// {
// title:'Second Name',
// description:'Second desc'
// }
// ]);
return (
<Container>
<Row>
<Col>
<Card.Body>
<DisplayCount />
<ListGroup>
todos.map((todo,index)=>(
<ListGroup.Item key={index}>
<h4>{todo.title}</h4>
<p>{todo.description}</p>
<Button
onClick={event=>deleteTodo(todo.id)} variant='danger' size="sm">
Delete
</Button>
</ListGroup.Item>
))
</ListGroup>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
const mapStateToProps=(state)=>{
console.log(state.todoReducer)
return{todos:state.todoReducer}
const mapDispatchToProps=(dispatch)=>({
deleteTodo:(id)=>(dispatch(deleteTodo(id)))
})
export default
connect(mapStateToProps,mapDispatchToProps)(DisplayTodos)
DisplayCount.jsx
import React from 'react'
return (
</Card.Body>
</Card>
const mapStateToProps=(state)=>({todos:state.todos})
const mapDispatchToProps=(dispatch)=>({})
delete operation
URL react-uuid - npm (npmjs.com)
install npm i react-uuid
import {v4} from 'uuid'
addTodo.jsx
addTodo({...todo,id:v4()})
DisplayTodos.jsx
const mapDispatchToProps=(dispatch)=>({
deleteTodo:(id)=>(dispatch(deleteTodo(id)))
})
● Arrow functions
● Classes
● Modules
● Destructuring Assignment
● Template Literals
What is Babel
mainly used to convert ES6 (2015) and above code into a backward
npm