Reputation: 977
I need to associate a few conditions with buttons in React. Here is the code:
class Stopwatch extends React.Component{
constructor(props){
super(props);
this.clickstart=this.clickstart.bind(this);
this.clickreset=this.clickreset.bind(this);
this.clickstop=this.clickstop.bind(this);
this.state={
timer:0
}
}
clickstart(){
this.incrementer=setInterval( ()=>this.setState({
timer:this.state.timer+1
}),1000);
}
clickreset(){
clearInterval(this.incrementer);// note what we did here
this.setState({
timer:0
})
}
clickstop(){
clearInterval(this.incrementer);
}
render(){
return(
<div className="stopwatch">
<h1>{convertfun(this.state.timer)}</h1>
<button onClick={this.clickstart}>Start</button>
<button onClick={this.clickreset}>Reset</button>
<button onClick={this.clickstop}>Stop</button>
</div>
);
}
}
I want the start button to be functional only if the timer
reads zero or it's value is zero. How do I achieve this in React?
Upvotes: 1
Views: 72
Reputation: 10844
class Stopwatch extends React.Component{
constructor(props){
super(props);
this.clickstart=this.clickstart.bind(this);
this.clickreset=this.clickreset.bind(this);
this.clickstop=this.clickstop.bind(this);
this.state={
timer:0
}
}
clickstart() {
this.incrementer=setInterval( ()=>this.setState({
timer:this.state.timer+1
}),1000);
}
clickreset() {
clearInterval(this.incrementer);// note what we did here
this.setState({
timer:0
})
}
clickstop() {
clearInterval(this.incrementer);
}
render() {
return(
<div className="stopwatch">
<h1>{convertfun(this.state.timer)}</h1>
// Change here
{this.state.timer == 0 && <button onClick={this.clickstart}>Start</button>}
<button onClick={this.clickreset}>Reset</button>
<button onClick={this.clickstop}>Stop</button>
</div>
);
}
}
Upvotes: 1
Reputation: 18592
you can add disabled attribute to button with condition
<button disabled={this.state.timer === 0} onClick={this.clickstart}>Start</button>
Upvotes: 0
Reputation: 28654
You can do it like:
return(
<div className="stopwatch">
<h1>{convertfun(this.state.timer)}</h1>
{this.state.timer == 0 && <button onClick={this.clickstart}>Start</button>}
<button onClick={this.clickreset}>Reset</button>
<button onClick={this.clickstop}>Stop</button>
</div>
);
Or
render(){
let button = null;
if(this.state.timer == 0) button = <button onClick={this.clickstart}>Start</button>;
return(
<div className="stopwatch">
<h1>{convertfun(this.state.timer)}</h1>
{button}
<button onClick={this.clickreset}>Reset</button>
<button onClick={this.clickstop}>Stop</button>
</div>
);
}
Upvotes: 1