The map function iterates an array and returns a map
. On the other hand, the forEach
function iterates an array and returns nothing.
Using forEach in JSX
The Array.forEach
function returns void.
If I forEach
my countries
array in JSX, it will not print anything.
export const App = () => {
const countries = ['USA', 'Canada', 'Australia', 'Japan', 'India']
return(
<>
{countries.forEach(country => {
return <div>{country}</div> //does not work
})}
</>
)
}
export default App
Using forEach in JSX
For rendering elements in JSX
, it is recommended to use Array.map
function instead of Array.forEach
. If I must use forEach
, I can push each modified array element into a second array. Then render the second array in JSX
. It doesn't make much sense. Doesn't it?
import { ReactElement } from "react"
export const App = () => {
const countries = ['USA', 'Canada', 'Australia', 'Japan', 'India']
let forEachCountries: ReactElement[] = []
const getForEachCountries = (): ReactElement[] => {
countries.forEach(country => {
forEachCountries.push(<li>{country}</li>)
})
return forEachCountries
}
return(
<ul>
{getForEachCountries()}
</ul>
)
}
export default App
Using Array.map in JSX
The map function iterates an array and returns a map
. I define how I want my map elements in the return statement. That way, I don't have to maintain a separate array to hold the modified array elements I want to render.
export const App = () => {
const countries = ['USA', 'Canada', 'Australia', 'Japan', 'India']
return(
<ul>
{countries.map((country) => {
return <li>{country}</li>
})}
</ul>
)
}
export default App
If you don't intend to create a map out of array elements or don't intend to render the contents of an array in JSX
, don't use the map
function. Use forEach
instead.