Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
163
rated 0 times [  166] [ 3]  / answers: 1 / hits: 120793  / 6 Years ago, mon, may 28, 2018, 12:00:00

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;

More From » reactjs

 Answers
41

You're trying to get the state of the date without explicitly setting it first. With that in mind call the getDate() method in something like, ComponentDidMount:



class App extends App.Component {
...
componentDidMount() {
this.getDate();
}
...
}


From there you should be able to retreive it in your render call:



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


Update:



constructor() is probably more suitable for this situation as no external requests are called to retrieve said data:



constructor(props) {
super(props);
this.state = {
date: new Date().toLocaleString()
};
}

[#54331] Thursday, May 24, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
demondp

Total Points: 154
Total Questions: 97
Total Answers: 99

Location: Mali
Member since Thu, Jul 9, 2020
4 Years ago
;