title: React music player
body: <p>I want to create a music player on a website. The Ideea is to choose a song and play it automaticly. The song must play on all pages and I need an play/pause button.
  I have created all the componentns but I have a bug. When I'm on the main page with the player component, the play/pause button does not work properly, If I stop the music I can't start it again, it works only on another pages. Here is the website <a href="https://thebrandbar.studio/#/" rel="nofollow noreferrer">https://thebrandbar.studio/#/</a></p>
  <p>App.js</p>
  <pre><code>import React, { useState } from 'react';
  import { HashRouter as Router, Route, Switch } from &quot;react-router-dom&quot;;
  import ScrollToTop from &quot;./helper/scrollToTop&quot;;
  
  import Home from &quot;./pages/Home&quot;;
  import Projects from &quot;./pages/Projects&quot;;
  import Team from &quot;./pages/Team&quot;;
  import ProjectPage from &quot;./pages/ProjectPage&quot;;
  import Error from &quot;./pages/Error&quot;;
  import TermsOfUse from &quot;./pages/TermsOfUse&quot;;
  import PrivacyPolicy from &quot;./pages/PrivacyPolicy&quot;;
  import Cookies from &quot;./pages/Cookies&quot;;
  
  
  const App = () =&gt; {
      const [currentTrackIndex, setCurrentTrackIndex] = useState(null);
      const [trackURL, setTrackURL] = useState('');
      const [playing, setPlaying] = useState(false);
  
      const callbackFunction = (currentTrackIndex, trackURL, playing) =&gt; {
          setCurrentTrackIndex(currentTrackIndex);
          setTrackURL(trackURL);
          setPlaying(playing);
      };
  
      const player = document.getElementById('player');
      const onPlayPauseClickHandler = (event) =&gt; {
          setPlaying(!playing);
          if (!playing) {
              player.play();
          } else {
              player.pause();
          }
      }
      const renderPlayBtn = () =&gt; {
          if (currentTrackIndex == null) {
              return;
          } else {
              return &lt;div className=&quot;play-btn&quot;&gt;
                  &lt;p onClick={onPlayPauseClickHandler} className={`play ${playing ? &quot;red-bg&quot; : &quot;blue-bg&quot;}`}&gt;
                      {playing ? &quot;SOUND OFF&quot; : &quot;SOUND ON&quot;}
                  &lt;/p&gt;
              &lt;/div&gt;
          }
      }
  
      return (
          &lt;&gt;
              &lt;Router&gt;
                  &lt;ScrollToTop /&gt;
                  &lt;Switch&gt;
                      &lt;Route exact path={`${process.env.PUBLIC_URL + '/'}`} &gt;
                          &lt;Home parentCallback={callbackFunction} player={player}/&gt;
                      &lt;/Route&gt;
                      &lt;Route
                          path={`${process.env.PUBLIC_URL + '/projects'}`}
                          component={Projects}
                      /&gt;
                      &lt;Route
                          path={`${process.env.PUBLIC_URL}/project/:projectId`}
                          component={ProjectPage}
                      /&gt;
                      &lt;Route
                          path={`${process.env.PUBLIC_URL + '/team'}`}
                          component={Team}
                      /&gt;
                      &lt;Route
                          path={`${process.env.PUBLIC_URL + '/terms'}`}
                          component={TermsOfUse}
                      /&gt;
                      &lt;Route
                          path={`${process.env.PUBLIC_URL + '/privacy'}`}
                          component={PrivacyPolicy}
                      /&gt;
                      &lt;Route
                          path={`${process.env.PUBLIC_URL + '/cookies'}`}
                          component={Cookies}
                      /&gt;
                      &lt;Route exact component={Error} /&gt;
                  &lt;/Switch&gt;
              &lt;/Router&gt;
              &lt;audio id=&quot;player&quot; src={trackURL} type=&quot;audio/mpeg&quot;&gt;&lt;/audio&gt;
              {
                  renderPlayBtn()
              }
          &lt;/&gt;
      );
  };
  
  export default App;
  </code></pre>
  <p>The main page</p>
  <pre><code>import React, { useState, useEffect } from 'react';
  import Loader from &quot;../container/Loader&quot;;
  import { Helmet } from &quot;react-helmet&quot;;
  import Cookies from &quot;../components/cookies&quot;;
  import LayoutDefault from &quot;../container/LayoutDefault&quot;;
  import Header from &quot;../components/header/Header&quot;;
  import HeroArea from &quot;../container/Hero&quot;;
  import MusicPlayer from &quot;../container/MusicPlayer&quot;;
  import FeaturedProjects from &quot;../container/FeaturedProjects&quot;;
  import Contact from &quot;../container/Contact&quot;;
  import Footer from &quot;../container/Footer&quot;;
  
  const Home = ({ parentCallback, player }) =&gt; {
      const [currentTrackIndex, setCurrentTrackIndex] = useState(null);
      const [trackURL, setTrackURL] = useState('');
      const [playing, setPlaying] = useState(false);
  
      const callbackFunction = (currentTrackIndex, trackURL, playing) =&gt; {
          setCurrentTrackIndex(currentTrackIndex);
          setTrackURL(trackURL);
          setPlaying(playing);
      };
  
      useEffect(() =&gt; {
          parentCallback(currentTrackIndex, trackURL, playing);
      });
  
  
      return (
          &lt;Loader&gt;
              &lt;Helmet&gt;
                  &lt;title&gt;TheBrandBar&lt;/title&gt;
              &lt;/Helmet&gt;
              &lt;Cookies /&gt;
              &lt;LayoutDefault className=&quot;template-color-2 bg_color--4&quot;&gt;
                  &lt;Header /&gt;
                  &lt;HeroArea /&gt;
                  &lt;MusicPlayer parentCallback={callbackFunction} player={player}/&gt;
                  &lt;FeaturedProjects /&gt;
                  &lt;Contact /&gt;
                  &lt;Footer /&gt;
              &lt;/LayoutDefault&gt;
          &lt;/Loader&gt;
      );
  };
  
  export default Home;
  </code></pre>
  <p>and Music Player component</p>
  <pre><code>import React, { useState, useEffect } from &quot;react&quot;;
  import { Container, Row, Col } from &quot;react-bootstrap&quot;;
  
  import DB from '../data/music/music.js';
  
  
  const Player = ({ parentCallback }) =&gt; {
  
    const [tracksList] = useState(DB);
    const [currentTrackIndex, setCurrentTrackIndex] = useState(null);
    const [trackID, setTrackID] = useState(null);
    const [trackURL, setTrackURL] = useState('');
    const [playing, setPlaying] = useState(false);
  
    useEffect(() =&gt; {
      parentCallback(currentTrackIndex, trackURL, playing);
    });
  
    const selectThisTrack = (event, trackID) =&gt; {
      let currentTrackIndex = 0;
      tracksList.map((track, index) =&gt; {
        if (track.id === trackID) {
          currentTrackIndex = index;
        }
        return track;
      });
      setCurrentTrackIndex(currentTrackIndex);
      setTrackID(tracksList[currentTrackIndex].id);
      setTrackURL(require(`../assets/player/music/${currentTrackIndex + 1}.mp3`));
      setPlaying(true);
      const player = document.getElementById('player');
      player.src = trackURL;
      player.preload = true;
      player.autoplay = true;
      player.loop = true;
      if (playing) {
        player.play();
      } else {
        player.pause();
      }
    }
    
  
    const renderCover = () =&gt; {
      if (!playing) {
        return &lt;img className=&quot;img-cover-default&quot; src={require(`../assets/player/covers/default.gif`)} alt=&quot;&quot; /&gt;
      } else {
        return &lt;img className=&quot;img-cover&quot; src={require(`../assets/player/covers/${currentTrackIndex + 1}.gif`)} alt=&quot;&quot; /&gt;
      }
    }
  
  
    return (
      &lt;&gt;
        &lt;Container&gt;
          &lt;Row&gt;
            &lt;Col className=&quot;play-list&quot; xs={{ span: 12, order: 2 }} lg={{ span: 4, order: 1 }}&gt;
              &lt;p className=&quot;your-rythm &quot;&gt;WHAT'S YOUR RYTHM?&lt;/p&gt;
              &lt;br /&gt;
              {DB.map((track, index) =&gt; (
                &lt;div
                  key={track.id}
                  index={index}
                  className={`song ${track.id === trackID ? &quot;selected&quot; : &quot;&quot;}`}
                  id={track.id === trackID ? &quot;activeTrack&quot; : &quot;&quot;}
                  onClick={(ev) =&gt; selectThisTrack(ev, track.id)}
                &gt;
                  &lt;p&gt;{track.title}&lt;/p&gt;
                &lt;/div&gt;
              ))}
            &lt;/Col&gt;
            &lt;Col xs={{ span: 12, order: 1 }} lg={{ span: 8, order: 2 }}&gt;
  
              &lt;div className=&quot;song-cover&quot;&gt;
                {
                  renderCover()
                }
              &lt;/div&gt;
  
            &lt;/Col&gt;
          &lt;/Row&gt;
        &lt;/Container&gt;
  
      &lt;/&gt;
    );
  };
  
  export default Player;
  </code></pre>
  <p>Thanks! :)</p>