Renderig Lists, Conditional Rendering, Click Events, Onclick, React hook(useState()), OnChange, Updater function, Update objects in State and Update Arrays in State
Rendering Lists
App.jsx
import Lists from './Lists.jsx'
function App(){
return(
<Lists />
);
}
export default App
Lists.jsx
function Lists(){
const fruits= ["apple", "orange", "Banana", "Pineapple"];
const listItems= fruits.map(fruit => <li>{fruit}</li>);
return(<ul>{listItems}</ul>);
}
export default Lists
Lists.jsx using sort, filter and map method
function Lists(){
const fruits= [{id: 1, name: "apple", calories: 95},
{id: 2, name: "orange", calories: 85},
{id: 3, name: "Banana", calories: 87},
{id: 4, name: "Pineapple", calories: 97}];
// fruits.sort((a, b)=> a.name.localeCompare(b.name));
// fruits.sort((a,b)=> a.calories - b.calories);
const highcalories= fruits.filter((fruit)=>fruit.calories>87);
// const listItems= fruits.map(fruit => <li key={fruit.id}>
// {fruit.name}:
// <b>{fruit.calories}</b></li>);
const listItems= highcalories.map(highcalories => <li key={highcalories.id}>
{highcalories.name}:
<b>{highcalories.calories}</b></li>);
return(<ul>{listItems}</ul>);
}
export default Lists
For displaying different lists
App.jsx
import Lists from './Lists.jsx'
function App(){
const fruits= [{id: 1, name: "apple", calories: 95},
{id: 2, name: "orange", calories: 85},
{id: 3, name: "Banana", calories: 87},
{id: 4, name: "Pineapple", calories: 97}];
const vegetables= [{id: 5, name: "Gobi", calories: 95},
{id: 6, name: "Shimla", calories: 85},
{id: 7, name: "Manali", calories: 87},
{id: 8, name: "Kattu", calories: 97}];
return( <>
<Lists items={fruits} category="Fruits" />
<Lists items={vegetables} category="Vegetables" />
</>
);
}
export default App;
Lists.jsx
function Lists(props){
const category = props.category;
const itemList = props.items;
const listItems = itemList.map((item) => (
<li key={item.id}>
{item.name}: <b>{item.calories}</b>
</li>
));
return(<>
<h3 className="list-category">{category}</h3>
<ul className="list-items">{listItems}</ul>
</>);
}
export default Lists;
Index.css
.list-category{
font-size: 2.5em;
font-weight: bold;
color: hsl(0, 0%, 20%);
margin-bottom: 10px;
text-align: center;
border: 3px solid;
border-radius: 5px;
background-color: hsl(185, 100%, 50%);
}
.list-items li{
font-size: 2em;
list-style: none;
color: hsl(0, 0%, 25%);
text-align: center;
margin: 0;
}
.list-items li:hover{
color: hsl(0, 0%, 45%);
cursor: pointer;
}
—--------
If we have empty lists
App.jsx
import Lists from './Lists.jsx'
function App(){
const fruits= [{id: 1, name: "apple", calories: 95},
{id: 2, name: "orange", calories: 85},
{id: 3, name: "Banana", calories: 87},
{id: 4, name: "Pineapple", calories: 97}];
const vegetables= [{id: 5, name: "Gobi", calories: 95},
{id: 6, name: "Shimla", calories: 85},
{id: 7, name: "Manali", calories: 87},
{id: 8, name: "Kattu", calories: 97}];
return( <>
{fruits.length > 0 ? <Lists items={fruits} category="Fruits" /> : null}
{vegetables.length > 0? <Lists items={vegetables} category="Vegetables" /> : null}
</>
);
}
export default App;
Lists.jsx
import PropTypes from "prop-types";
function Lists(props){
const category = props.category;
const itemList = props.items;
const listItems = itemList.map((item) => (
<li key={item.id}>
{item.name}: <b>{item.calories}</b>
</li>
));
return(<>
<h3 className="list-category">{category}</h3>
<ul className="list-items">{listItems}</ul>
</>);
}
Lists.propTypes ={
category: PropTypes.string,
items: PropTypes.arrayOf(PropTypes.shape({id: PropTypes.number,
name: PropTypes.string,
calories: PropTypes.number})),
}
Lists.defaultProps={
category: "category",
items: [],
}
export default Lists;
—------------------
Click Events for example button:
Button.jsx
function Button(){
let count=0;
const handleClick= (name)=>{
if(count<3){
count++;
console.log(`${name} you click me ${count} times/s`);
}
else{
console.log(`${name} Stop Clicking me`);
}
}
return(
<>
<button onClick={()=> handleClick("Saurav")}>Click Me</button>
</>
);
}
export default Button
App.jsx
import Button from './Button.jsx'
function App(){
return(<>
<Button></Button>
</>);
}
export default App
React Hooks
A react hook is a special function that allows functional components to use react features without writing class components
UseState()
A react hook that allows the creation of stateful variable and a setter function to update its value in the virtual DOM
import {useState} from 'react';
function MyComponents(){
const [name, setName]= useState("Guest");
const [age, SetAge]= useState(0);
const [isEmployed, SetIsEmployed]= useState(false);
const incrementAge=() =>{
SetAge(age+1);
}
const updateName= ()=>{
setName("Saurav");
}
const toggleEmployedStatus=()=>{
SetIsEmployed(!isEmployed);
}
return(<>
<div>
<p>Name: {name}</p>
<button onClick={updateName}>Set Name </button>
<p>Age: {age}</p>
<button onClick={incrementAge}>Set Age </button>
<p>Is employed: {isEmployed ? "yes" : "no"}</p>
<button onClick={toggleEmployedStatus}>Toggle Status</button>
</div>
</>
);
}
export default MyComponents
Value updating using useState()
Increment Decrement Counter
import {useState} from 'react'
function Counter(){
const [count, setCount]= useState(0);
const increment= () =>{
setCount(count+1);
}
const decrement= () =>{
setCount(count-1);
}
const reset=() =>{
setCount(0);
}
return(
<div className="counter-container">
<p className="content-display">{count}</p>
<button className="decrement-button" onClick={decrement}>Decrement</button>
<button className="increment-button" onClick={increment}>Increment</button>
<button className="reset-button" onClick={reset}>Reset</button>
</div>
)
}
export default Counter
onChange method using
import {useState} from 'react'
function Counter(){
const [name, setName]= useState("Saurav");
const [quantity, setQuantity]= useState(1);
const [comment, setComment]=useState("");
const [payment, setPayment]= useState("");
const [shipping, setShipping]= useState("");
function handleNameChange(event){
setName(event.target.value);
}
function handleQuantityChange(event){
setQuantity(event.target.value);
}
function handleCommentChange(event){
setComment(event.target.value);
}
function handlePaymentMethod(event){
setPayment(event.target.value);
}
function handleShippingChange(event){
setShipping(event.target.value);
}
return(
<>
<div>
<input value={name} onChange={handleNameChange} />
<p>Name: {name}</p>
<input value={quantity} onChange={handleQuantityChange} type="number"/>
<p>Quantity: {quantity}</p>
<input value={comment} onChange={handleCommentChange} placeholder="Enter the instructions for delievery"/>
<p>Commnet: {comment}</p>
<select value={payment} onChange={handlePaymentMethod}>
<option value="">Select an Option</option>
<option value="Visa">Visa</option>
<option value="Master Card">Master Card</option>
</select>
<p>Payment: {payment}</p>
<label>
<input type="radio" value="Pick Up"
checked={shipping==="Pick Up"}
onChange={handleShippingChange}/>
Pick Up
</label>
<label>
<input type="radio" value="Delievery"
checked={shipping==="Delievery"}
onChange={handleShippingChange}/>
Delievery
</label>
</div>
</>
);
}
export default Counter
It is a event handler used primarily with form elements ex <input>, <text area>, <select>, <radio>, triggers a function every time the value of the input changes
—--------
Colour picker
import { useState } from 'react';
function Color(){
const [color, setColor]= useState();
function handleColorChange(event){
setColor(event.target.value);
}
return (
<>
<div className="color-picker-container">
<h1>Color Picker</h1>
<div className="color-display" style={{backgroundColor: color}}>
<p>Selected Color: {color} </p>
</div>
<label>Select a Color:</label>
<input type="color" value={color} onChange={handleColorChange} />
</div>
</>
);
}
export default Color;
—------------------
Update function use only count+1 like setCount(c=> c+1);
In decrement setCount(c=>c-1);
import {useState} from 'react'
function Counter(){
const [count, setCount]= useState(0);
const increment= () =>{
setCount(c=> c+1);
setCount(c=> c+1);
setCount(c=> c+1);
}
const decrement= () =>{
setCount(count-1);
}
const reset=() =>{
setCount(0);
}
return(
<div className="counter-container">
<p className="content-display">{count}</p>
<button className="decrement-button" onClick={decrement}>Decrement</button>
<button className="increment-button" onClick={increment}>Increment</button>
<button className="reset-button" onClick={reset}>Reset</button>
</div>
)
}
export default Counter
—-------------
To Update objects in STates
(to change object we use onChange event handler)
import {useState} from 'react'
function Counter(){
const [car, setCar]= useState({year: 2024,
make: "Ford",
model: "Mustang"});
function handleYearChange(event){
setCar(c=> ({...c, year: event.target.value}));
}
function handleMakeChange(event){
setCar(c=> ({...c, make: event.target.value}));
}
function handleModeChange(event){
setCar(c=> ({...c, model: event.target.value}));
}
return(<div>
<p>Your favorite car is: {car.year} {car.make} {car.model} </p>
<input type="number" value={car.year} onChange={handleYearChange} /><br/>
<input type="text" value={car.make} onChange={handleMakeChange}/><br/>
<input type="text" value={car.model} onChange={ handleModeChange}/><br/>
</div>
)
}
export default Counter
—------------
Update arrays in State using onClick event handler
import {useState} from 'react'
function Counter(){
const [foods, setFoods]= useState(["Apple", "Orange", "Pineapple", "Strawberry"]);
function handleAddFood(){
const newFood= document.getElementById("foodInput").value;
document.getElementById("foodInput").value="";
setFoods(f=>[...f, newFood]);
}
function handleRemoveFood(index){
setFoods(foods.filter((_, i)=> i !== index));
}
return(<div>
<h2>Lists of food items</h2>
<ul>
{foods.map((food, index)=>
<li key={index} onClick={()=>handleRemoveFood(index)}>
{food}</li>)}
</ul>
<input type="text" id="foodInput" placeholder="Enter Your Food"/>
<button onClick={handleAddFood}>Add Food</button>
</div>);
}
export default Counter
Comments
Post a Comment