I have an JSX Element which I assign as to a variable:
const test = <prettyDate value={new Date()} />
When I console.log(prettyDate(test.props))
I get the following:
So, logically I thought I can do this console.log(prettyDate(test.props.children))
and get this 2022/09/16 12:51
but instead I get an error. Cannot destructure property 'value' of 'undefined' as it is undefined.
How can I get this date out of there?
CodePudding user response:
You can directly access props with prop name like console.log(test.props.value)
CodePudding user response:
The type of introspection you're describing is not idiomatic React. If you need some data in a parent component and also in some descendant component, that data should be passed as props (or held in some state accessible by both components).
If you simply want to get a date string in the format depicted in your screenshot (2022/09/16 12:51
), then you can create a function to do that and then use it in your component with a date instance:
function padN (n: number, maxLength = 2, fillString = '0'): string {
return String(n).padStart(maxLength, fillString);
}
function formatDate (date: Date): string {
const y = date.getFullYear();
const mo = date.getMonth() 1;
const dom = date.getDate();
const h = date.getHours();
const m = date.getMinutes();
return `${y}/${padN(mo)}/${padN(dom)} ${padN(h)}:${padN(m)}`;
}
const dateStr = formatDate(new Date());
console.log(dateStr);
Compiled JS from the TS Playground link:
"use strict";
function padN(n, maxLength = 2, fillString = '0') {
return String(n).padStart(maxLength, fillString);
}
function formatDate(date) {
const y = date.getFullYear();
const mo = date.getMonth() 1;
const dom = date.getDate();
const h = date.getHours();
const m = date.getMinutes();
return `${y}/${padN(mo)}/${padN(dom)} ${padN(h)}:${padN(m)}`;
}
const dateStr = formatDate(new Date());
console.log(dateStr);