Mir Stephen
Mir Stephen

Reputation: 1927

Error: Objects are not valid as a React child (found: Wed Nov 06 2019 19:50:56 GMT+0500 (Uzbekistan Standard Time))

Newbie in react, trying to play with it, but I got this problem.

I wrote some JavaScript, but I get the above stated error:

class Content extends Component {
  constructor() {
    super();
    this.date = {new Date()};
  }
  state = {};

  render() {
    return (
        <div className="alert alert-success">{this.date}</div>  
  }
}

if i add something like this.date = 'hello world' and then return it, that works fine, but if I try to assign new Date() for this.date I get this error. How do I solve it? Thank you!

Upvotes: 0

Views: 237

Answers (1)

Clarity
Clarity

Reputation: 10873

You need to convert the date to string before displaying it, since new Date() returns an object:

class Content extends Component {
  constructor() {
    super();
    this.date = new Date();
  }
  state = {};

  render() {
    return <div className="alert alert-success">{this.date.toString()}</div>;
  }
}

Upvotes: 3

Related Questions