Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print JavaScript new Date() in React?

I cannot print simple JavaScript dates inside of React.

import React, { Component } from 'react';
import './ActivityWarningText.css';

class ActivityWarningText extends Component {

        render() {
            const str = new Date();
            return(
          <div>
            <h1>All activity is recorded. {str}</h1>
          </div>
         )
        }

}

export default ActivityWarningText;

I get this error:

Objects are not valid as a React child (found: Wed Apr 25 2018 18:09:03 GMT+0400 (Arabian Standard Time)). If you meant to render a collection of children, use an array instead.
    in h1 (at index.js:17)
    in div (at index.js:16)
    in ActivityWarningText (at index.js:34)
    in component (created by Route)
    in Route (at index.js:34)
    in div (at index.js:33)
    in div (at index.js:30)
    in Router (created by BrowserRouter)
    in BrowserRouter (at index.js:29)
    in App (at withAuthentication.js:36)
    in WithAuthentication (at index.js:14)

This works however, str.getFullYear()

like image 240
TheBlackBenzKid Avatar asked Mar 04 '26 20:03

TheBlackBenzKid


1 Answers

Date object has to be casted to string. You can try with

{str.toString()}

or

{`${str}`}
like image 194
hsz Avatar answered Mar 07 '26 08:03

hsz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!