Unable to display Date in JSX in ReactJS

Tags: , ,



Following is my code which is working fine if I initialize test with a string, though if I changed it to new Date() its throwing error. Let me know what I am doing wrong as I just started with React.

Code –

import React from 'react';
import ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';

    class App extends React.Component {
        render() {
            //let test = 'this is a string'; // WORKING FINE
            let test = new Date();
            return (
                <div>
                    <h1>Hello World</h1>
                    <p>{test}</p>
                </div>
            );
        }
    }

    ReactDOM.render(<App />, document.getElementById('root'));
    registerServiceWorker();

Error –

Objects are not valid as a React child (found: Fri Jul 21 2017 02:11:18 GMT+0530 (India Standard Time)). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.

Answer

You are seeing that because Date is an object not a string. To get it to work as you have it with no libraries:

import React from 'react';
import ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';

class App extends React.Component {
    render() {
        //let test = 'this is a string'; // WORKING FINE
        let test = new Date();
        return (
            <div>
                <h1>Hello World</h1>
                <p>{test.toString()}</p>
            </div>
        );
    }
}

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

Call the toString() method on the date object.



Source: stackoverflow