How to work with array using useState hooks

In this tutorial we are going to to learn about how to work with array using useState hook 


First we are going to create an array , in this array we are having an id , name , age . and simplay console the data using console.log(bioData)


var bioData = [

   {

     id: 0,

     myname: "tejas",

     age: 23

   },

   {

     id: 0,

     myname: "savio",

     age: 22

   },

   {

     id: 0,

     myname: "manoj",

     age: 23

   }

 ];

 console.log(bioData);


Now we are going to use the useState hook and initialize the array which is bioData.  


 

 const [myArray, setmyArray] = useState(bioData);


Now create function clearArray and define the updated state which is setmyArray with a blank square bracket. This blank square bracket use to clear the data  


const clearArray = () => {

   setmyArray([]);

 };


And finally the return part where we can return the array element using map method and we also have a button with passing clearArrar function to clear the screen . Once you refresh the page value comes back to the screen.

return (

   <div>

     <>

       {myArray.map((empData) => (

         <h1>

           Name:{empData.myname} age:{empData.age}

         </h1>

       ))}

       <button onClick={clearArray}>cleare</button>

     </>

   </div>

 );}


Output:-








Post a Comment

0 Comments