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