I loop on an object and I would like to display a result based on the Object.entries.
However the loop stops at the first return.
How can I get and display in one time what the components return to me? In a variable maybe ? Thanks
export const ResultItem: React.FC<Props> = (props:Props) => {
const search = props
const provideItem = () => {
for (const [key, value] of Object.entries(search.result))
{
switch(key) {
case "companies":
return <SearchCompany result={search.result[key]}/>
case "medias":
return <SearchMedias result={search.result[key]}/>
case "contracts":
return <SearchContracts result={search.result[key]}/>
case "contacts":
return <SearchContacts result={search.result[key]}/>
}
}
}
return (<div>{provideItem()}</div>)
}
Since you're returning a component, the execution of the for loop ends on the first iteration. An easy fix would be to create an array of items and push components into it, then render them at once.
export const ResultItem: React.FC<Props> = (props:Props) => {
const search = props
const provideItem = () => {
const items = []
for (const [key, value] of Object.entries(search.result))
{
switch(key) {
case "companies":
items.push(<SearchCompany result={search.result[key]}/>)
case "medias":
items.push(<SearchMedias result={search.result[key]}/>)
case "contracts":
items.push(<SearchContracts result={search.result[key]}/>)
case "contacts":
items.push(<SearchContacts result={search.result[key]}/>)
}
}
return items
}
return (<div>{provideItem()}</div>)
}