Using react to change a button's name on click

I’m part way through my Pomodoro Clock project: https://codepen.io/Crimson_Macaw/pen/ebRNzg and cannot get my start button to change it’s name to stop after I’ve clicked it.

I’ve written a function within the main App component as shown below:

handleStartStopButton = () => {
   const renderStartStop = () => { 
     if(this.state.timerStop){
      return <button>Start</button>
    }else{
      return <button>Stop</button>
    }
  }
   
   return(
   <div>
     {renderStartStop}
     </div>
   )
   }

There is another component called Display to which I pass this handleStartStopButton function (referred to as this.props.startStop) as props:

class Display extends React.Component{
  render(){
    return(
    <div className = "display">
                {this.props.startStop}
      {this.props.minutes + ":" + this.props.seconds} 

      </div>
    )
  }
}

As you can see in my codepen, this button isn’t showing up. I’d greatly appreciate any help on this.

Also, if anyone knows how to make the seconds show up as 09, 08, 07, etc., instead of 9,8,7,6, then please let me know as well, since I’ve spent a few days trying to get it to display correctly and can’t figure it out.

handleStartStopButton() is not doing much, does it really warrant it’s own function ? Since all you are using it is to toggle what the button displays.
Here is how I would handle it, since timerStop (or timerStart) are already in your app’s state.

In your main app component I would pass the above’s state as a prop,

       <StartButton  start = {this.handleStart} 
          startStop = {this.state.timerStop}/>

Then, in the StartButton button component I would simply put a conditional display

class StartButton extends React.Component{
  render(){
    return(
    <button onClick = {this.props.start}> {this.props.startStop ? 'Start' : 'Stop'}</button>
    )
  }
}

This is of course one of many ways to do it, I just don’t see the need of the handleStartStopButton() function when it is not doing much, unless of course you have other future plans for it.

1 Like

Thanks, I’ve changed it as per your advice.

I used the handleStartStopButton() function because I was simply confused as to how to structure my syntax. Anyway, it’s completely superfluous now.

Is the syntax of what I wrote clear to you ? or is there still some confusion ? … happy to elaborate if the latter

Everything you wrote is perfectly clear, it’s just that I’m rarely able to come up with code like that by myself, even though it’s absolutely basic react.

I see, I can assure you that is absolutely normal, looking at react code I wrote when I first started disgusts me, not that I’m anything close to perfect now, but with every new project you build you get better, so keep at it and also keep your earlier code for reference (so you can be disgusted in the future :slight_smile: )