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 –
JavaScript
x
20
20
1
import React from 'react';
2
import ReactDOM from 'react-dom';
3
import registerServiceWorker from './registerServiceWorker';
4
5
class App extends React.Component {
6
render() {
7
//let test = 'this is a string'; // WORKING FINE
8
let test = new Date();
9
return (
10
<div>
11
<h1>Hello World</h1>
12
<p>{test}</p>
13
</div>
14
);
15
}
16
}
17
18
ReactDOM.render(<App />, document.getElementById('root'));
19
registerServiceWorker();
20
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.
Advertisement
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:
JavaScript
1
20
20
1
import React from 'react';
2
import ReactDOM from 'react-dom';
3
import registerServiceWorker from './registerServiceWorker';
4
5
class App extends React.Component {
6
render() {
7
//let test = 'this is a string'; // WORKING FINE
8
let test = new Date();
9
return (
10
<div>
11
<h1>Hello World</h1>
12
<p>{test.toString()}</p>
13
</div>
14
);
15
}
16
}
17
18
ReactDOM.render(<App />, document.getElementById('root'));
19
registerServiceWorker();
20
Call the toString() method on the date object.