user14590058
user14590058

Reputation:

Date() constructor is rendering my page completely blank

When I'm using the built-in Date() constructor it's rendering my page completely blank

Current Output

Expected Output

import './ExpenseItem.css';

function ExpenseItem() {
 const expenseDate = new Date(2022, 1, 1)

  return (
      <div className='expense-item'>
          <div>{expenseDate}</div>
          <div className='expense-item__description'>
              <h2>Car Insurance</h2>
              <div className='expense-item__price'>$269.64</div>
          </div>
      </div>
  );
}

export default ExpenseItem; 

Upvotes: 1

Views: 209

Answers (2)

lunatic
lunatic

Reputation: 1

** Because Date is an object and you cant render object as child**

// toDateString() will convert it into sting.

const expenseDate = new Date(2022, 1, 1).toDateString();

Upvotes: 0

Emanuele Scarabattoli
Emanuele Scarabattoli

Reputation: 4489

This is because you are trying to render a Date as a React child and Objects are not valid as a React child (the reason behind your blank screen).

Change your code to be like:

const expenseDate = new Date(2022, 1, 1).toLocaleString();

In this way you will have a string instead, that is a valid React child.

Check the documentation on how to change your date-to-string format:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

Upvotes: 1

Related Questions