1

Code that works with map() function:

function Garage() {
  const cars = ['Ford', 'BMW', 'Audi'];
  return (
    <>
        <h1>Who lives in my garage?</h1>
        <ul>
        {cars.map((car) => <li>I am a {car}</li>)}
      </ul>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);

I'm trying to make it work when I replace map() function with forEach() function, but it doesn't work and I get Unexpected token errors:

return (
    <>
        <h1>Who lives in my garage?</h1>
        <ul>        
        {        
        function myFunction(item ) {        
        return <li>I am a {item} </li>
          }        
        cars.forEach(myFunction)     
   
        }        
            </ul>
    </>
  );

I tried putting myFunction outside return method, for some reason there are no errors then, but still nothing is outputted except "Who lives in my garage?":

function Garage() {
  const cars = ['Ford', 'BMW', 'Audi'];
  function myFunction(item) {        
        return <li>I am a {item} </li>
     } 
  return (
    <>
        <h1>Who lives in my garage?</h1>
        <ul>         
            {cars.forEach(myFunction)}       
            </ul>
    </>
  );
}
Matt Perry
  • 25
  • 4
  • 1
    Map returns an array of components. For each doesn’t return anything and has no purpose in react template logic. You’ll want to stick to map, filter and anything that returns an array. – FreddieMixell Mar 22 '23 at 03:59
  • I think I got it, in React array=list. It doesn't even matter if we use
  • or any other tag, as soon as React notices array in output it treats it as a list....
  • – Matt Perry Mar 22 '23 at 05:00