Home > Enterprise >  Switch case return multiple component
Switch case return multiple component

Time:10-31

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>)
}

CodePudding user response:

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>)
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You are getting only the first return because is that how a function works(first return "returns" that value and end the function), the return is for the function not for the "for" statement the return is ending the function.

You can use a map function to handle the component decision, and the return statement now can be used inside. This should work:

 const provideItem = () => {
        return Object.entries(search.result).map(seR => {
            const [key, value] = seR;
            switch (key) {
                case "companies":
                    return <SearchCompany result={value} />
                case "medias":
                    return <SearchMedias result={value} />
                case "contracts":
                    return <SearchContracts result={value} />
                case "contacts":
                    return <SearchContacts result={value} />
            }
        })
    }
  • Related