How to Use findIndex in React JS

How to Use findIndex in React JS

Hye, Today I wanted to share how you can use findIndex in react js.

What is findIndex

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test. To simplify, it gives us the first index in an array that meets the function needs.

What Can you do with findIndex() In react js

You can create a Next and Previous button that can loop through an array. For Example, I have created a react app that will loop through an array of songs.

Capture.PNG

This is what the array will look like. I named the fileData.js

import { v4 as uuidv4 } from 'uuid';

function chillhop(){
    return[
        {
            name:"Cruising",
            artist:"Evil Needle",
            cover:" https://chillhop.com/wp-content/uploads/2021/04/cb0cc6270d7f2e1bb13e44e8832bd5c9b2a61080-1024x1024.jpg",
            id:uuidv4(),
            active:true,
            color:['#EC5C4D','#DEA25B'],

        },
        {
            name:"Low Rider",
            artist:"Evil Needle",
            cover:"https://chillhop.com/wp-content/uploads/2021/04/cb0cc6270d7f2e1bb13e44e8832bd5c9b2a61080-1024x1024.jpg",
            id:uuidv4(),
            active:false,
            color:['#EC5C4D','#DEA25B'],

        },
        {
            name:"On The Moon",
            artist:"SwuM",
            cover:"https://chillhop.com/wp-content/uploads/2021/03/74d62bc9370a68e440c1b98eaf650344f0a7faea-1024x1024.jpg",
            id:uuidv4(),
            active:false,
            color:['#283430','#513B32'],

        }
    ]
}
export default chillhop;

next, in App.js set the songs using useState()

const [songs,setSongs]=useState(data());

then set the current displaying song also using useState()

const [currentSong,setCurrentSong]=useState(songs[0]);

The next thing you need to do is create a component named player.js

and create an event handler that will handle the next and previous buttons.

 //Event Handler 
    const skipTrackHandler = async (direction)=>{
        let currentIndex = songs.findIndex((song)=>song.id === currentSong.id);
        if(direction === "skip-forward"){
          await  setCurrentSong(songs[(currentIndex+1)%songs.length]);
          activeLibraryHandler(songs[(currentIndex+1)%songs.length]);
        }
       if(direction==="skip-back"){
           if(((currentIndex-1)%songs.length===-1))
           {
              await setCurrentSong(songs[songs.length-1]);
              activeLibraryHandler(songs[songs.length-1]);
               if(isPlaying) audioRef.current.play();
               return;
           }
         await  setCurrentSong(songs[(currentIndex-1)%songs.length]);
         activeLibraryHandler(songs[(currentIndex-1)%songs.length]);
       }
       if(isPlaying) audioRef.current.play();

    };

and lastly also in player.js in return()

    return (
        <div className="player">
            <div className="time-control">
                <p>{getTime(songInfo.currentTime)}</p>
                <div style={{background:`linear-gradient(to right,${currentSong.color[0]},${currentSong.color[1]})`}} className="track">
                <input 
                min={0}
                 max={songInfo.duration || 0} 
                 value={songInfo.currentTime} 
                 onChange={dragHandler} 
                 type="range" 
                />
                 <div style={trackAnim} className="animate-track"></div>
                 </div>
                <p>{songInfo.duration ? getTime(songInfo.duration) : "0:00"}</p>
            </div>
            <div className="play-control">
                <FontAwesomeIcon onClick={()=>skipTrackHandler('skip-back')} className="skip-back" size="2x" icon={faAngleLeft}/>
                <FontAwesomeIcon 
                onClick={playSongHandler} 
                className="play"
                size="2x" 
                icon={isPlaying ? faPause : faPlay}/>
                <FontAwesomeIcon  onClick={()=>skipTrackHandler('skip-forward')} className="skip-forward" size="2x" icon={faAngleRight}/>
            </div>

        </div>

    )

And that is it. You have used findIndex in react js. P.s. I have learned to use this by finishing Dev Ed React course https://developedbyed.com/. The course has helped me a lot in my journey of being a Front-end Developer.

Do Give your opinion and question and please give a like if it has helped you also as it will help me a lot. Thank You in Advanced.