Search code examples
react-nativebuttonaudiostylesexpo

React Native Toggle Style


I have a button which first load the audio and play, and If I click on him, it pauses the music as I wanted:

    const navigation = useNavigation();
    const soundObject = new Audio.Sound();

    let playandpauseflag = 0;
    let loadsoundonceflag = false;

    async function loadsound(){ 
        try {
           await soundObject.loadAsync(require('./hello.mp3'));
        } catch (error) {
            alert('error');
        }
    };

    async function loadplayandpausesong(){
        //just load sound once
        if(loadsoundonceflag){
            await loadsound();
            loadsoundonceflag = false; //next time will not load the sound, just play
        }
        if(playandpauseflag == false){
            await soundObject.playAsync(); //play
            playandpauseflag = true;
        }else{ //not false next time (true)
            await soundObject.pauseAsync(); //pause
            playandpauseflag = false;
        }
    }

I would like to change his style according to 'play' or 'pause'. This is the way I'm rendering the styles:

<FontAwesome5
     name="play" //if I put "pause" I'll have the 'pause' design that I want when I click to play the button
></FontAwesome5>

I tried name= playandpauseflag ? "pause" : "play", but it doesn't work correctly. It is a way, but it is bugging my loading application and I would like to know If I could do it by another way. Thank you so much!


Solution

  • Try using useState. For example,

    const [playState, setPlayState] = useState('pause');
    
    const onClick = () => {
        if (playState === 'play') {
          setPlayState('pause');
        } else {
          setPlayState('play');
        }
    };
    
    return (
        <FontAwesome5 name={playState}></FontAwesome5>
    );