How to know if audio ended in React js with toggle button

I have built a toggle button that turns on & off the audio, but my problem is how can I return the toggle button to off when the audio has finished and it’s building with react js if you can help me with some hints.

import { React, useState } from 'react';
import './playSong.css';
Import music from './THREE.mp3';

const PlaySong = () => {
const [activeSong, setActiveSong] = useState(false);
var [saveSong, setSaveSong] = useState({});

var drake = {
    value: 3,
    name: 'Energy',
    artist: 'Drake',
    audio: music, //

function handlePlayPause() {
    let states = !activeSong;

    if (states) {  
        playSong(drake); // load song and play it
    else {
        togglePause(saveSong); // pause song


function playSong(drake) {
    var Song = new Audio(;;
    return Song;

function togglePause(saveSong) {

return (
    <div className="container">
        <div className="button r" id="button-4">    
            <input type="checkbox" className="checkbox" onChange={handlePlayPause} checked= 
            {activeSong} />
            <div className="knobs" />
            <div className="layer" />

 export default PlaySong

>Solution :

Have you considered running all of your audio code through <audio> tag?

It has many events which you can supply handlers for.

Specifically the ended or onended (maybe onEnded) event is the one you may want to look at.

Leave a Reply