-2

I'm following a course and I have this issue where I can't reference/access object instances passed as a prop. For example, lets call this component CalenderDate.js and inside I have the following code:

function CalenderDate(props) {
    return (
        <div className="date">
            <div>
                <div>{props.date.toLocaleString('en-US', { month: 'long' })}</div>
                <div>Date</div>
                <div>Year</div>
            </div> 
        </div>
    )
}

And then in App.js I do this:

function App() {
const array = [
{
 date: new Date(2020, 11, 23),
 words:"string of text"},
{
 winningNumber: 7,
 message: "Winning Number 7"}
]

return(
<>
<CalenderDate date = array[0].date></CalenderDate>
</>
)
}

Somehow, in CalenderDate.js prop.date becomes undefined and now, on my react page the console shows an error,

Cannot read properties of undefined (reading 'toLocaleString')

Help, please!

Wumi
  • 1
  • 1
  • 1
    I think this line has problem `const array = [date: new Date(...)]` there is no such data structure like this in js. – thelonglqd Jun 22 '22 at 15:58
  • Check your console for errors, thats not a way of defining an array with an key/ – 0stone0 Jun 22 '22 at 15:58
  • Does this answer your question? [Best way to store a key=>value array in JavaScript?](https://stackoverflow.com/questions/1144705/best-way-to-store-a-key-value-array-in-javascript) – 0stone0 Jun 22 '22 at 15:59

2 Answers2

1

Have you tried to console.log your props, or to put a breakpoint while debugging? This helps you a lot!

Anyway, try with

<CalenderDate date ={array[0].date} />

Little tip: please try to avoid using key-words as variable names, it's confusing and not really readable. I'd say: switch from 'array' to 'dateProp' or something similiar.

Little tip #2: always have in mind the structure you're using: const array = [ date: new Date(...)] means nothing. I supposed you wanted an array, so:

const myArray = []

then you wanted one or more objects inside it, so:

const myArray = [ { } ]

each object has a key and a value, so:

const myArray = [ { key: value, key2 : value2, etc } ]

want more objects inside? Then go:

const myArray = [ {key: value}, { key2: value2}, ..., { keyn : valuen} ]

raindrop
  • 9
  • 2
  • I tried this but no luck. Also, console.logging my props: all the other props came back with the assigned values. But the date object doesn't, it came back with undefined. – Wumi Jun 22 '22 at 16:04
  • Have you tried declaring it in a const? Something like: const myDate = new Date (year, month, day)? – raindrop Jun 24 '22 at 08:09
0
 function App() {
    const array = new Date(2020, 11, 23)
        
    return(
        <>
           <CalenderDate date={array} />
    )
  };

The way you declared the data for the date is not the proper way of defining data in javascript, it look more like you are defining an object inside an array opening without the curly braces for the object.