1

I am trying to show blinking text using react:

class BlinkLable extends React.Component {
    constructor(props) {
    super(props);
    this.state = {showlabel: true,
                 label: this.props.label
                 };
    this.myFunction = this.myFunction.bind(this);

}

myFunction()  
{
    var sLb = ! (this.state.showlabel);
    this.setState({showlabel: sLb});
}

componentDidMount() {
    setTimeout(this.myFunction, 3000)
 }

render() {
    return (
      <div>
        {(this.state.showlabel)?this.state.label:''}
      </div>
     );
    }
}

ReactDOM.render(
   <BlinkLable label='MY MESSAGE'/>,
      document.getElementById('labelId')
);

However, after it shows MY MESSAGE, this message dissapears and never comes back. What could be the problem?

Jose Cabrera Zuniga
  • 2,348
  • 3
  • 31
  • 56

3 Answers3

1

You need to use setInterval() method.

componentDidMount() {
    setInterval(this.myFunction, 3000)
 }

More Info: 'setInterval' vs 'setTimeout'

Jude Niroshan
  • 4,280
  • 8
  • 40
  • 62
1

Modify this function to:

myFunction()  
{
    this.setState((prevState) => {
      return { 
        showlabel: !prevState.showLabel
      }
    });
}
Win
  • 2,083
  • 2
  • 11
  • 14
1

class BlinkLable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {showlabel: true,
                 label: this.props.label
                 };
    this.myFunction = this.myFunction.bind(this);
  }
  myFunction(){
    var sLb = ! (this.state.showlabel);
    this.setState({showlabel: sLb});
  }
  render(){
    return (
      <div>
        {(this.state.showlabel)?this.state.label:''}
      </div>
     );
  }
  componentDidUpdate() {
     setTimeout(this.myFunction, 2000)
  }
  componentDidMount(){
    setTimeout(this.myFunction, 2000)
  }
}


ReactDOM.render(
   <BlinkLable label='MY MESSAGE'/>,
      document.getElementById('labelId')
);
<div id="labelId"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

you need to know react's component life cycle.

componentDidMount() is called only when a component is mounted.

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here.

Therefore if you want to keep blinking, add componentDidUpdate().

HyeonJunOh
  • 734
  • 1
  • 8
  • 22