Home > Software design >  How to count for each mapped element?
How to count for each mapped element?

Time:07-28

trying to write an onClick for my React project. I have results mapped out. I am trying to keep a count for each of those elements, but with a global variable (index) it breaks if I use more than one clickable element per session. I have tried to do id.index, adding (id) index etc but am stumped. How do I properly use the unique id's to track the index for each card? Thanks

function onClick(id) {
    let index = 0;
    index  ;
    if (index >= 1) {
      dosomething
    } else if (index === 0) {
      dosomethingelse
    }
  }

CodePudding user response:

It's not clear what and how you want to count and onclick events.

Assuming that you need to keep track of clicks on each element/id:
You can use the useRef hook and keep it a global object to track the number of clicks per id.

const clicksPerId = useRef({});

function onClick(id) {
   if (!clicksPerId.current[id]) {
       clicksPerId.current[id] = 0;
   }
   clicksPerId.current[id]  ;

   // whatever you want to do with the clicks count
}

CodePudding user response:

I'm kinda confused by your question to be honest however for working with arrays in javascript / React maybe you'll find some of these helpful

  1. Getting the array length

const MyComponent = () => {

  const [myArray, setMyArray] = useState([1, 2]);
  
  // find the length of the array
  const getArrayLength = () => {
    return myArray.length;
  }

  return (
    <p>hello there</p>
  )
}

  1. Doing something with the index of a maped component:

const MyComponent = () => {

  const [myArray, setMyArray] = useState([1, 2]);
  
  const handleClick = (index) => {
    // do somthing with the index of the el
  };

  return (
    <>
      { myArray.map((el, index) => {
          return (
            <p
              key={index}
              onClick={() => handleClick(index)}
             >
              el number { el }
            </p>
          )
        }) 
      }
    </>
  )
}

  • Related