Home > Mobile >  Can't access object passed as a prop
Can't access object passed as a prop

Time:06-23

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!

CodePudding user response:

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} ]

CodePudding user response:

 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.

  • Related