Search code examples
javascriptreactjsaudiofeathericons

How to place an icon on an if then statement for a react button


I'm trying to create a button that will display a different icon and message when it is clicked. However, I'm unsure of how to include the icon inside the 'if then' statement within the < button > element. I'm quite new to React.

My code is below:

import React, { setState, useState, useEffect } from "react";
import { Pause, 
          Play  } from 'react-feather';

function AudioPlayer() {
  // use Audio constructor to create HTMLAudioElement
  const audioTune = new Audio("<YOUR_AUDIO_FILE_PATH.mp3>");

  // variable to play audio in loop
  const [playInLoop, setPlayInLoop] = useState(false);

  // variable to play audio in loop
  const [isPlay, isPlaying] = useState(0);

  // load audio file on component load
  useEffect(() => {
    audioTune.load();
  }, []);

  // play audio sound
  const playSound = () => {
    audioTune.play();
    isPlaying(1);
  };

  // pause audio sound
  const pauseSound = () => {
    audioTune.pause();
  };

  // stop audio sound
  const stopSound = () => {
    audioTune.pause();
    audioTune.currentTime = 0;
    isPlaying(0);
  };

  const handlePlaying = () => {
    if (isPlay) {
      stopSound();
    } else {
      playSound();
    }
  };

  return (
    <div>
      <div className="App">
    
        <button onClick={handlePlaying}>
          {isPlay ? <Pause /> "pause" : <Play/> "listen to this page"}
        </button>
      </div>
    </div>
  );
}

export default AudioPlayer;

I get an error here {isPlay ? <Pause /> "pause" : <Play/> "listen to this page"}

The error is:

SyntaxError
/src/components/Audio2.js: Unexpected token, expected ":" (57:30)

I've tried to insert the icon within the "" marks, but that is just displaying the button code as string.

Thanks for your help


Solution

  • You can do it like this

    <button onClick={handlePlaying}>
      {isPlay ? (
        <>
          <Pause /> Pause
        </>
      ) : (
        <>
          <Play /> Listen to this page
        </>
      )}
    </button>;