'How do I write Mulitiple if statments inside array.map() call

I have an array of data, and inside a react component I would like to render some JSX based on a property of each item in the array.

This is the code so far:

  return (
        <div>
            <p> Render CMS Components for `{location.pathname}`</p>

            {componentItems.map(componentItem => (

                if (componentItem.Name == "namehere") {
                <p>render compnent here</p>

            }
            if (componentItem.Name == "namehere2") {
                <p>render compnent 2 here</p>

            }
            if (componentItem.Name == "namehere3") {
                <p>render compnent 3 here</p>

            }

            ))}

        </div>
    );
}
export default RenderCmsComponents;


Solution 1:[1]

You can use && operator for this:

import { Fragment } from 'react'

// ...
 const conditionalRender(item) {
     return (
         <Fragment>
                componentItem.Name == "namehere" && <p>render compnent here</p>
                componentItem.Name == "namehere2" && <p>render compnent 2 here</p>
                // etc..
         </Fragment>     
    )
 }

 return (
        <div>
            <p> Render CMS Components for `{location.pathname}`</p>
            {componentItems.map(conditionalRender)}

        </div>
    );
}
export default RenderCmsComponents;

Solution 2:[2]

you just need to write "return" keyword in if statement

export default function App() {
  var arr = ['abc' , 'pqr' , 'xyz'];
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      {
        arr.map(i => {
          if(i == 'abc'){
            return <p>ABC</p>
          }
          if(i == 'xyz'){
            return <p>XYZ</p>
          }
        })
      }
    </div>
  );
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Silvan Bregy
Solution 2 anks_patel