I want to output the current date in my componnent. In the console my code works, but the React console says:
"bundle.js:14744 Uncaught RangeError: Maximum call stack size exceeded"
My component looks like that:
import React from 'react';
var FontAwesome = require('react-fontawesome');
export class Date extends React.Component {
constructor() {
super();
var today = new Date(),
date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
this.state = {
date: date
};
}
render() {
return (
<div className='date'>
<FontAwesome name='calendar' />{this.state.date}
</div>
);
}
}
Yeah, I know I'm a pretty beginner, but maybe someone can help me. I googled for hours -.-
Thx alot!
This question is related to
javascript
reactjs
OPTION 1: if you want to make a common utility function then you can use this
export function getCurrentDate(separator=''){
let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();
return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}
and use it by just importing it as
import {getCurrentDate} from './utils'
console.log(getCurrentDate())
OPTION 2: or define and use in a class directly
getCurrentDate(separator=''){
let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();
return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}
You can use the react-moment package
-> https://www.npmjs.com/package/react-moment
Put in your file the next line:
import moment from "moment";
date_create: moment().format("DD-MM-YYYY hh:mm:ss")
Source: Stackoverflow.com