Imagine that GenerateGreetings requires greeting more than 50 people. It would not be logical to create 50 or more lines of code, knowing that arrays are objects that have the forEach method.
function GenerarSaludos() { // ojo con la notaciónde mayuscula inicial para diferenciar de componentes HTML
let personas = [
{ nombre: 'Carlos', apellidos: 'Cuesta Iglesias' },
{ nombre: 'Jordan', apellidos: 'Walke' },
{ nombre: 'Brendan', apellidos: 'Eich' }
];
return (
<div>
<Saludo nombre={personas[0].nombre} apellidos={personas[0].apellidos}/>
<Saludo nombre={personas[1].nombre} apellidos={personas[1].apellidos}/>
<Saludo nombre={personas[2].nombre} apellidos={personas[2].apellidos}/>
</div>
);
}
Make the necessary adjustments to make this improvement in the code.
This you should put instead of your return, I assume it's react, you should specify that in your question
What the code does would be, create an empty array in which to store the greetings that you will generate when going through the
personas
Then with the forEach it tells you that for each item inpersonas
it save the specific item in a person variable and do what is between curly braces . Between curly braces then for each item it adds one<Saludo/>
to your array for that person, but since you will surely want to render that array then you must not forget to add thekey
so that rails can differentiate the items when it has to re-render some part of your array. You can read more about rendering arrays at https://es.reactjs.org/docs/lists-and-keys.html And in case it is not required to use forEach, I would recommend for cases like this to use map as in the link above, since this is already optimized to go through and generate an array with an item for each item it goes through