Salman Lari
Salman Lari

Reputation: 29

Why props alone are being used in called React function component?

I was learning React and I came to a point which created confusion. Everywhere I was using props while writing Function components.

I always use props.profile and it works fine. But in one code component, I had to write const profiles=props; and it worked fine.

I tried using const profiles=props.profile; and also I tried using inside return in 'Card' function component

{props.profile.avatar_url} but both of them failed

Below is my code which works fine

const Card=(props)=>{
  const profiles=props; //This I dont understand
  return(
    <div>
      <div>
        <img src={profiles.avatar_url} width="75px" alt="profile pic"/>
      </div>
      <div>
        <div>{profiles.name}</div>
        <div>{profiles.company}</div>
      </div>
    </div>
  );
}

const CardList=(props)=>{
  return(
    <div>
      {testDataArr.map(profile=><Card {...profile}/>)}
    </div>
  );
}

Can someone please help me understand why I can't use const profiles=props.profile?

What are the other ways to achieve the correct result?

Upvotes: 0

Views: 96

Answers (2)

ravibagul91
ravibagul91

Reputation: 20755

Your testDataArr might be this,

testDataArr = [{avatar_url:"",name:"",company:""},{avatar_url:"",name:"",company:""},{avatar_url:"",name:"",company:""}]

Now when you do this,

{testDataArr.map(profile=><Card {...profile}/>)}

here profile = {avatar_url:"",name:"",company:""},

and when you do,

<Card {...profile}/>

is equivalent to,

<Card avatar_url="" name="" company=""/>

In child component, when you do this,

const profiles=props;

here props = {avatar_url:"",name:"",company:""}

So you can access it's values,

props.avatar_url

props.name

props.company

But when you do this,

const profiles=props.profile

profile key is not present in {avatar_url:"",name:"",company:""} object and it fails.

Upvotes: 2

Laurentiu Turcu
Laurentiu Turcu

Reputation: 140

OK. Here is the issue, the props object does not contain a profile attribute, but IT IS the profile attribute. Becouse you are spreading the profile variable when you render the Card element (in the CardList), you basically are writing:

<Card avatarUrl={profile.avatarUrl} comapny={profile.comany} />

Instead, you should do

<Card profile={profile} />

and then in your Card component access the data this way

const Card = (props) => {
  const profile = props.profile
}

or even simpler

const Card = ({profile}) => {
  return <div>{profile.comany}</div>
}

Upvotes: 1

Related Questions