The worm The worm - 1 month ago 7
React JSX Question

Displaying react javascript in html

I have this function that sets the date from two weeks ago:

dateTwoWeeksAgo: function(){
var twoWeeksAgo = new Date().toDateString();
this.setState({twoWeeksAgo: twoWeeksAgo});
},


I have this code that calls this function. But it is not working. how do I display a variable I am setting the state of or returning from a function?

<h2 className="headings" id="commitTotal"> Commits since {this.dateTwoWeeksAgo} : {this.state.commits.length} </h2>

Answer

Option 1: In order to display the value of twoWeeksAgo held on you state you can:

<h2 className="headings" id="commitTotal"> Commits since {this.state.twoWeeksAgo} : {this.state.commits.length} </h2>

The actual method which updates your state - dateTwoWeeksAgo() - could be called for example in the componendDidMount lifefycle method.
https://facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount

Here is a demo: http://codepen.io/PiotrBerebecki/pen/LRAmBr

Option 2: Alternatively, you can just call a method which returns the required date like so (http://codepen.io/PiotrBerebecki/pen/NRzzaX),

const App = React.createClass({
  getInitialState: function() {
    return {
      commits: ['One', 'Two']
    };
  },

  dateTwoWeeksAgo: function() {
    return new Date().toDateString();
  },

  render: function() {
    return (
      <div>
        <h2 className="headings" id="commitTotal"> Commits since {this.dateTwoWeeksAgo()} : {this.state.commits.length} </h2>
      </div>
    );
  }
})

Code option 1:

const App = React.createClass({
  getInitialState: function() {
    return {
      twoWeeksAgo: null,
      commits: ['One', 'Two']
    };
  },

  componentDidMount: function() {
    this.dateTwoWeeksAgo();
  },

  dateTwoWeeksAgo: function() {
    var twoWeeksAgo = new Date().toDateString();
    this.setState({twoWeeksAgo: twoWeeksAgo});
  },

  render: function() {
    return (
      <div>
        <h2 className="headings" id="commitTotal"> Commits since {this.state.twoWeeksAgo} : {this.state.commits.length} </h2>
      </div>
    );
  }
})

ReactDOM.render(
  <App />,
  document.getElementById('app')
);
Comments