I’m brand new to React, and still pretty shaky on Typescript and Javascript (super fast paced Revature training course), and I’m attempting to make a React component that will iterate through an array of Account objects that would be passed into the component. This is the code as it currently exists:
export default function AccountSummaryList(accountList:Account[]){
const listOfAccountSummaries = accountList.map((account,index)=>{
return(
<li key={index}>
<AccountSummary{...account}/>
</li>
);
})
return(
<ul>
{listOfAccountSummaries}
</ul>
)
}
I’ve been looking around, and none of the solutions that I’ve found appear to apply. One source said that the issue is that the compiler doesn’t see the accountList as actually being an array due to the time difference between the program starting and the object instantiation, but I can’t verify if that’s what is happening for me. The thing is, I can brute force the code to work by declaring the listOfAccountSummaries variable like this:
const listOfAccountSummaries = (
<>
<li>
<AccountSummary{...accountList[0]}/>
</li>
<li>
<AccountSummary{...accountList[1]}/>
</li>
</>
)
So the issue is something to do with how the compiler reads the accountList variable. If the issue is indeed a matter of the compiler not recognizing that the accountList variable is an array of Account objects, I have yet to find a solution that resolves that. One solution I found suggests validating that the array is actually an array with this approach:
const listOfAccountSummaries = accountList && accountList.map && accountList.map((account,index)=>{
return(
<li key={index}>
<AccountSummary{...account}/>
</li>
);
})
and while that does get the app to compile without any errors, it also doesn’t display the list of account summaries.
I’m really struggling to understand how Typescript works, so any explanation y’all can give me as to why this problem is arising would be incredibly appreciated.
Ned is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.