Jd Li
Jd Li

Reputation: 175

react.js How to change the ball's class every seconds?

  1. I am a beginer to learn react.js. I want to change the ball's class in every seconds?one second is "on",another is "off".
  2. I am try to use setInterval but there have error Error: Invariant Violation: EzLampComp.render(): A valid ReactComponent must be returned.
  3. my code is here. How to solve ??

ez-lamp style:

.ez-lamp{
  display : inline-block;
  margin : 5px;
  width : 30px;
  height : 30px;
  border-radius : 50%;
}
.ez-lamp.on{
  opacity : 1;
  background : -webkit-radial-gradient(30% 30%,white 5%,red 95%);
}
.ez-lamp.off{
  opacity : 0.5;
  background : -webkit-radial-gradient(30% 30%,#888 5%,red 95%);
}

Ezlamp component:

var EzLampComp = React.createClass({
  render : function(){
    var onoff = this.props.onoff;                   
    setInterval(function(){
      if(onoff="on")
      return <span className = "ez-lamp off"></span>; 
      else
      return <span className = "ez-lamp off"></span>; 

    },1000);                                    
  }
});
ReactDOM.render(
  <EzLampComp onoff="on"/> , //JSX
  document.querySelector("#content"));

Upvotes: 0

Views: 895

Answers (1)

vijayst
vijayst

Reputation: 21856

setInterval should be called from componentDidMount and should toggle only the state.

getInitialState() {
  return {
    onoff: this.props.onoff
  }
}

componentDidMount() {
  setInterval(function() {
    this.setState({
      onoff: !this.state.onoff
    }, 1000);
  }
}

Upvotes: 3

Related Questions