reactjsindexingarray.prototype.map

How to print a index inside a map in React component?


I'm quite new to React. Could someone help me print an index using the console.log function in this mapping? Many thanks in advance

{projectData.map((_, index) => (
    <button
    key={index}`
    onClick={() => goToSlide(index)}
    className={index === currentIndex ? 'active slider-button' : 'slider-button'}>
    { `Project ${index + 1}` }
    </button>
 ))}

Solution

  • You should use return keyword to console.log(index)

    {projectData.map((_, index) => {
        console.log(index);
        return (
          <button
            key={index}`
            onClick={() => goToSlide(index)}
            className={index === currentIndex ? 'active slider-button' : 'slider-button'}>
            { `Project ${index + 1}` }
          </button>
        )
     })}