Skip to main content

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}: &nbsp;

    //                                          <b>{fruit.calories}</b></li>);


    const listItems= highcalories.map(highcalories => <li key={highcalories.id}>

                                              {highcalories.name}: &nbsp;

                                            <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

Popular posts from this blog

Why Profile Creation in SEO is Important?

Importance of Profile Creation in SEO Profile creation for SEO is a crucial component of creating a strong online presence.   By establishing profiles on various platforms, businesses and individuals can establish their identities and showcase their knowledge and increase their visibility to the people they want to reach.   Profiles function like virtual business cards that offer useful information about the business such as contact information web links, contact information, along with social handles.   Additionally, the creation of profiles allows the user to customize them with images or logos to help to increase the brand's recognition.   From an SEO standpoint, profiles aid in link-building efforts by providing the possibility of including backlinks to relevant blogs or websites.   Because search engines favor reliable backlinks that come from trustworthy sources, having a properly optimized profile is crucial to improving ranking on search engines.   ...

The Power of Profile Creation on Social Media

Create profiles on various social networking platforms, directories, forums, and other platforms in order to expand your online visibility and presence. An SEO profile provides multiple advantages, from increasing your presence online and making new contacts to opening accounts on various social media sites to create more awareness for yourself or your business, increasing website traffic or growing followership across platforms. Reaching a wider market can be accomplished by advertising your goods and services on various websites through profiles. Doing this will establish you as an industry expert online, increasing visibility on search engine results pages (SERPs), and website rankings by creating profiles on high-quality sites, and increasing brand recognition online. Backlinks are an essential element of SEO and, when created on high-quality sites, can substantially increase the credibility and trustworthiness of your site. By creating profiles across various platforms and sites, ...

what are the benefits of Profile Creation in SEO?

Harness the power of profile creation to supercharge your SEO strategy! In today's digital world, visibility is vital to success; make sure you stand out and capture the attention of search engines and customers alike. Profile creation allows you to benefit from a multitude of advantages with regard to your website's ranking and overall visibility. Whether you're an experienced business owner or new on the entrepreneurial path, understanding the importance of profile creation for SEO is necessary if you want to stay ahead in this competitive game. Let’s explore how its potential can take your website to greater heights! The creation of profiles is an excellent way to increase traffic and position on the Search Engine Results Page. It is not extremely hard to build a profile, but you must enter the right information. Having your image name as your username makes your site appear more open and trustworthy. Profiles are a decent source of improvement over the immediate site in...