Published 17 Jun, 2022

React.Js - Typescript how to pass an array of Objects as props?

Category React
Modified : Jan 31, 2023

React is a highly popular js library which makes writing frontend a breeze, it makes javascript make more sense by laying out UIs in components which acts and behaves independently. React is one of the go to libraries for modern web development.

There are 2 suggested solutions in this post and each one is listed below with a detailed description on the basis of most helpful answers as shared by the users. I have tried to cover all the aspects as briefly as possible covering topics such as Reactjs, Typescript, Arrays, React Props, React Typescript and a few others. I have categorized the possible solutions in sections for a clear and precise explanation. Please consider going through all the sections to better understand the solutions.

Solution 1

You can simply return this in the User component:

return (
 <UsersList users= />
)

Then the UsersList component will become:

const UsersList = ( { users } : UsersListProps) => {
 if(!users?.length){
   return(
     <div>
       <h1>No users found</h1>
     </div>
   );
 }
 return(
  <ul>
   ) => (
     <UserIListtem
      key= 
      name= 
      id= 
      image= 
      places= 
      placeCount=/> 
   ))}
  </ul>
 );
}

And the UserIListtem component:

const UserIListtem = ({ name: user, id, image, placeCount, places: placeName }: User) => {
 return (
  <li>
   <div>
    <div>
     <img src= alt=/>
    </div>
    <div>
     <h2></h2>
     <h3></h3>
     </div>
   </div>
  </li>
 )
}

Remember to also change the UsersListProps interface to:

export interface UsersListProps {
 users: User[];
}

export interface User {
 id: number;
 name: string;
 image: string;
 placeCount: number;
 places: string;
}

Solution 2

Here's the final solution you can try out in case no other solution was helpful to you. This one's applicable and useful in some cases and could possiblty be of some help. No worries if you're unsure about it but I'd recommend going through it.

You can just replace props with users: Array and then send the whole array and load the data from there in your UserIListtem.


Final Words

React has become the go to library for frontend development. It has a wide community support and a multitude of ready made components. These were few of the solutions reported helpful by the community. Hope it turns out helpful for you as well.

Java is to JavaScript what Car is to Carpet.
Chris Heilmann