Search code examples
javascriptreactjsreact-hooksreact-routertimer

Trying to switch 2 different audio file with useParams hook but it doesn't work


Hello I'm developing a meditation app with a timer and a play and pause button. When you press play the timer and the music starts. For the music I'm using react audio player, I want to switch the audio file, I've tried to use useParams hook but it doesn't work.

In the src of audioplayer I have set this {sound === "rain" ? RainMp3 : WindMp3} (sound is equal to useParams() ), I set the url to be 'rain', but it doesn't work, when I console.log() sound with the url rain, sound it's effectively rain but it doesn't work the same.

Timer.js

import { Link, useParams } from "react-router-dom";
import AudioPlayer from "react-audio-player";

// import audio
import RainMp3 from "../audio/rain.mp3";
import WindMp3 from "../audio/wind.mp3";

const Timer = () => {

  let sound = useParams();
  console.log(sound);

 //...

  return (

     //...

      <div className="container">
        <div className="audio">
          {isRunning && time > 0 ? (
            <AudioPlayer src={sound === "rain" ? RainMp3 : WindMp3} autoPlay />
          ) : null}
      </div>

    //...

};

Home.js

import { Link } from "react-router-dom";

//import Header
import Header from "./Header";

const Home = () => {
  return (
    <>
      <main>
        <div className="Home">
          <div className="titleHome">
            <Header />
          </div>
          <div className="btnBoxHome linkBox">
            <div>
              <Link to="/Timer/rain">
                <button className="btn">Rain</button>
              </Link>
            </div>
            <h3>Or</h3>
            <div>
              <Link to="/Timer/wind">
                <button className="btn">Wind</button>
              </Link>
            </div>
          </div>
        </div>
      </main>
    </>
  );
};

App.js

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

// COMPONENTS
import Timer from "./components/Timer";
import Home from "./components/Home";
// STYLE
import "./components/style/style.css";

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/Timer/:sound" element={<Timer />} />
      </Routes>
    </Router>
  );
}

Solution

  • In timer.js just change

    let sound = useParams()
    

    To

    let { sound } = useParams ()
    

    Hope This Helps 😄!