Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display date in React.js using state?

I'm trying to display date using React.js but for some reason it's not displaying anything.

I'm a beginner so I'm sorry if I'm asking a stupid question, but I can't figure out why it's not working. Can someone please help me? Thanks so much!

class App extends React.Component {
  state = {
    date: ""
  };

  getDate() {
    var date = { currentTime: new Date().toLocaleString() };

    this.setState({
      date: date
    });
  }

  render() {
    return (
      <div class="date">
        <p> ddd {this.state.date}</p>
      </div>
    );
  }
}

export default App;
like image 457
Leon Bogod Avatar asked May 28 '18 13:05

Leon Bogod


2 Answers

You can use JavaScript codes by using ${} like following:

<span className="xyz">
      {`${new Date().toLocaleString()}`}
</span>

Please note that you need to use the Grave Accent character (i.e.` ) around the ${}.

Or if you want to convert a date-time string to local value, you can follow this solution:

<span className="xyz">
      {`${formData.updatedAt ? new Date(formData.updatedAt).toLocaleString() : ""}`}
</span>
like image 166
MJBZA Avatar answered Sep 30 '22 11:09

MJBZA


Here's a simple way:

class App extends React.Component {
  state = {date: new Date()}

  render() {
    return (
      <div class="date">
        <p> ddd {this.state.date.toLocaleDateString()}</p>
      </div>
    );
  }
}

export default App;

Cheers!

like image 38
nurealam siddiq Avatar answered Sep 30 '22 13:09

nurealam siddiq