Search code examples
javascriptreactjsreact-props

Unable to access the props directly in Child Component


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;

Solution

  • 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