I'm doing a React JS Course. I want to render the day and date by using props and toLocaleString method. But the app just crashes. Here's my code
function ExpenseDate(props) {
const month = props.date.toLocaleString("en-US", { month: "long" });
const day = props.date.toLocaleString("en-US", { day: "2-digit" });
const year = props.date.getFullYear();
return (
<div>
<div>{month}</div>
<div>{year}</div>
<div>{day}</div>
</div>
);
}
export default ExpenseDate;
When I export & use that component & refresh the server. The server shows this: Undefined (reading 'toLocaleString')
Please help. I'm in a rush!
CodePudding user response:
You need to verify if the fields have values. If you're using babel, this will work:
function ExpenseDate(props) {
const month = props.date?.toLocaleString("en-US", { month: "long" });
const day = props.date?.toLocaleString("en-US", { day: "2-digit" });
const year = props.date?.getFullYear();
return (
<div>
<div>{month}</div>
<div>{year}</div>
<div>{day}</div>
</div>
);
}
CodePudding user response:
okay, I thought I was crazy I'm literally doing this same react course on the exact same step and I'm trying to figure out wtf I'm doing wrong? I added the ? but now the date doesn't display.
Okay, if you move further ahead he corrects the problem, within the return on the ExpenseItem.js file you need to add the follow:
<ExpenseDate date={props.date} />