Home > database >  React Typescript access keys of prop array
React Typescript access keys of prop array

Time:05-29

I have my Homepage which sends a modal component a profile like this.

<ProfileOverviewModal
     open={openProfile}
     onClose={closeAllModals}
     onCreateProfile={onCreateProfile}
     profile={state.profil}
/>

In my ProfileOverviewModal.tsx I have this props

type Props = {
  open: boolean
  onClose: () => void
  onCreateProfile: (values: ProfileModalFormValues) => void
  profile: Profil[]
}

When I console.log(profile) everything seems to work. This shows up in the console:

{Firstname: 'Eddy', Lastname: 'Browkin', __typename: 'Profil'}

But I can not access profile.Firstname && profile.Lastname for example

return (<h1>{profile.Firstname}</h1>)

Why is that? Any one can point me in the right direction.

CodePudding user response:

Your profile prop expects array of object of type Profil, if you are passing single object then just change the prop as

type Props = {
  open: boolean
  onClose: () => void
  onCreateProfile: (values: ProfileModalFormValues) => void
  profile: Profil
}

And if you are passing array of profile then change you way you are accessing as below

return (<h1>{profile[index].Firstname}</h1>)

CodePudding user response:

The issue is that you have defined the type as Profile[] which is expecting array of Profiles. Just remove the [] from the type and you won't be seeing any error.

CodePudding user response:

Try this

return (
   <div>
      <h1> {profile.Firstname} </h1>
   </div>
)

Either use div tag or fragment i.e <> here h1 tag or everything else </>. Also. in props , onCreateProfile does'nt seem to be correct. Please check that also.

  • Related