phantom phantom - 2 months ago 16
React JSX Question

toggle play/pause in react with audio

I have made an audio player, with one button to play and pause. This should perform a play action if the

playing
is false, and will pause if
playing
is true.

I am not sure if it is because thinking in React still isn't 100% natural to me, but I cannot figure out how to do this.

Can anyone point me in the right direction?

Please see my code below.

var Player = React.createClass({

getInitialState: function(){
return{
songs:[],
playing: false
}
},

audio: new Audio,

playSong: function(){
this.setState({playing = true});
this.audio.src = this.state.songs[this.props.song];
this.audio.play();
},

pauseSong: function() {
this.setState({playing = false});
this.audio.pause();
},

render: function(){
return(
<p onClick={...}>Play/Pause<p/>
)
}


I guess I can create another function to toggle play and pause like the following. Is this the best way to do this?

togglePlayPause:function() {
if(this.state.playing === false) {
this.playSong();
}else {
this.pauseSong();
}
},
render: function(){
return(
<p onClick={this.togglePlayPause}>Play/Pause<p/>
)
}

Answer
var Player = React.createClass({

   getInitialState: function(){
       return{
           songs:[],
           playing: false
       }
   },
   audio: new Audio,
   playSong: function(){
    console.log("play")
    this.setState({playing:true});
    this.audio.src = this.state.songs[this.props.song];
    this.audio.play();

   },

   pauseSong: function() {
    console.log("pause");
    this.setState({playing:false});
    this.setState({playing = false});
    this.audio.pause();

   },

  render:function(){
      return(
        <p onClick={this.state.playing ? this.pauseSong : this.playSong}>Play/Pause</p>
      )
   }
  });

ReactDOM.render(
  <Player/>,
  document.getElementById('container')
);

you can do this with ternary onclick you can decide which function you want to call. probably are typo but you need to do this.setState({key:value}); and not this.setState({key = value});

https://jsfiddle.net/reactjs/69z2wepo/