dwigt
dwigt

Reputation: 611

Updating variable in react

I have what seems to be a very simple question. In the following code I can not update a variable reference but I can set it directly, can you tell me why?

This updates the HTML element correctly:

startTimer() {
    let timerOutput = this.timerOutput.innerHTML = this.state.timer.toLocaleTimeString();
}

Using this code however nothing happens in the DOM:

startTimer() {
        let timerOutput = this.timerOutput.innerHTML;
        timerOutput = this.state.timer.toLocaleTimeString();
    }

Printout of the entire Timer container component:

export class Timer extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {timer: new Date()};
      }

    startTimer() {
        let timerOutput = this.timerOutput.innerHTML;
        timerOutput = this.state.timer.toLocaleTimeString();
        // timerOutput = this.state.timer.toLocaleTimeString();
        console.log(this.state.timer);
    }

    handleClick(e) {
        this.startTimer(e);
    }


  componentDidMount() {

  }

  render() {

    return (
      <section>
        <div id="timerOut"
        ref={(output) => {this.timerOutput = output }}
        ></div>
        <button onClick={this.handleClick.bind(this)} value="Click me" />;
        <h2>It is {this.state.timer.toLocaleTimeString()}.</h2>
      </section>
    );
  }
}

export default Timer;

Upvotes: 0

Views: 44

Answers (2)

Tiago Alves
Tiago Alves

Reputation: 2316

When you are doing this:

let timerOutput = this.timerOutput.innerHTML;
timerOutput = this.state.timer.toLocaleTimeString();

You are not changing the element's innerHTML but just a copy of that. In order to change the DOM you have to do:

this.timerOutput.innerHTML = this.state.timer.toLocaleTimeString();

Edit: to be clear, it does answer your question but it's not the "React way" of doing this. You should manage state with setState().

Upvotes: 2

Nandu Kalidindi
Nandu Kalidindi

Reputation: 6280

You need to use setState to re-render the component. Try changing the startTimer() method as follows. If all you are trying is to show the current time each time you click on the button.

startTimer() {
    this.setState({timer: new Date()})
}

Upvotes: 1

Related Questions