Reputation: 400
I have stored the data in a file (details.js) as a JavaScript Object, then I'm trying to pass it as a prop from MainComponent to ChildComponent. Well the prop is accessible in ChildComponent but I could access it with props.ChildDetails[0].name
instead of props.name
directly as shown in the Official documentation
What am i missing?
details.js
export const DETAILS=[
{
id:0,
profile:'/assests/images/john.png',
name:'John Doe',
}
]
MainComponent.js
import React,{useState} from 'react';
import Child from './ChildComponent';
import {DETAILS} from '../Shared/details';
function MainComponent(){
return(
<>
<Child ChildDetails={DETAILS}/>
</>
);
}
export default MainComponent;
ChildComponent.js
import React from 'react';
function ChildComponent(props){
console.log(props.name) //Output:undefined
console.log(props.ChildDetails[0].name) //Output:John Doe
return(
<div></div>
);
}
export default ChildComponent;
Upvotes: 0
Views: 436
Reputation: 4838
here is where you passed the object
<Child ChildDetails={DETAILS}/>
and here is how you tried to use it
console.log(props.name) //Output:undefined
since you defined the name as ChildDetails
there is no such thing as props.name instead you must say
console.log(props.ChildDetails)
and if you want to get access to an name
you should declare the index if not react does not know which index you want to use, so as you did before
props.ChildDetails[0].name
Upvotes: 1
Reputation: 147
Because Details is object. Try something like:
function ChildComponent({ ChildDetails }){
const { name } = ChildDetails[0]
...
}
That's not even React. That's JavaScript
Edit. Oops. People said that's an array. I thought it's just an object. Fixed code a bit
Upvotes: 1