useState Array example

  • To Clear all items
    • <button onClick={() => SetCricketData([])}>Clear</button>
  • To Remove all items – RemoveCricketer is invoked
 
				
					import React, { useState } from "react";
import cricketData from "./CricketData";

const UseStateArray = () => {
  console.log(cricketData);
  const [cktData, SetCricketData] = useState(cricketData);

  const RemoveCricketer = (id) => {
    let freshCricketData = cktData.filter((x) => x.id !== id);
    SetCricketData(freshCricketData);
  };

  return (
    <>
      <div className="myClass">
        {cktData.map((data) => {
          const { name, category, id } = data;
          return (
            <div key={id}>
              <ul>
                <li>{name}</li>
                <li>{category}</li>
                <button onClick={() => RemoveCricketer(id)}>Remove</button>
              </ul>
              <hr />
            </div>
          );
        })}
        <button onClick={() => SetCricketData([])}>Clear</button>
      </div>
    </>
  );
};
export default UseStateArray;

				
			
				
					const CricketData = [
  {
    id: 1,
    name: "SKY",
    category: "Batsman",
    details: "He is MR 360",
  },
  {
    id: 2,
    name: "Ishan Kishan",
    category: "Batsman",
    details: "Explosive batsman with a double century",
  },
  {
    id: 3,
    name: "Siraj",
    category: "Bowler",
    details: "fast bowler from Hyderabad",
  },
];

export default CricketData;

				
			

Leave a Comment