5

I am a beginner in React. I have a pretty simple code. (There are other questions which seems to be duplicate of this but they ain't. Please read the contents also not just the question heading before marking duplicate.)

import React, { Component } from 'react';
class Likes extends Component {
  render() {
    var music=["linkin park", "led zaplin", "regina spector", "bruno mars"];
    return(
    {
      music.forEach(function (value, index, array) {
          <h1>{value}</h1>
       })
      }
    );
  }
}
export default Likes;

Is it correct way or should I use state. I wanted to keep it as simple as possible. But I'm getting this.(see attached image)

What is that I am missing. What else I should know.

PS: I dont have any other separate component or code. Everything is there inside the class itself.

Tanzeel
  • 4,174
  • 13
  • 57
  • 110
  • 3
    Use `.map` and `return` the

    – Jonas Wilms Aug 07 '19 at 15:32
  • Ok. But then I'll have to set `keys` also. Correct me If i'm wrong. – Tanzeel Aug 07 '19 at 15:33
  • use below code music.map((value, index) {

    {value}

    })
    – Puneet Bhandari Aug 07 '19 at 15:34
  • @TanZeel index will provide you key that you can use, see above – Puneet Bhandari Aug 07 '19 at 15:35
  • @Punneet Yes. But I've been told that its not the best way. As index will change as we add or remove elements from that `music` array. Is it so? – Tanzeel Aug 07 '19 at 15:36
  • @Tanzeel As you remove or add elements to array, your index will get reset automatically with new array. – ravibagul91 Aug 07 '19 at 15:38
  • 1
    @tanzeel if you add/remove value from array and setState then component will automatically rerender and index will initialize again – Puneet Bhandari Aug 07 '19 at 15:41
  • 2
    The problem with your code is a `syntaxError` and not the use of `forEach` (though you will have to use map due to the fact that `map` returns an array that react will use to render but `forEach` itself does not return anything. Try `[1,2,3].forEach(a => a)` and `[1,2,3].map(a => a)` in your browser console to see the difference). The syntaxError can be fixed like ```const elements = [] music.forEach(function(value, index, array) { elements.push(

    {value}

    ) }) return elements``` With `forEach` you build an array of elements urself but `map` does this automatically
    – Lucky Soni Aug 07 '19 at 17:02
  • @LuckySoni. Actually I implemented the solution and got my problem solved. Wanted to answer my question but I cannot do so as someone has marked my question duplicate. Thanks anyways. – Tanzeel Aug 07 '19 at 17:14

1 Answers1

9

You need to iterate array using map,

{music.map(function (value, index, array) {
    return <h1 key={index}>{value}</h1>
  })
}
ravibagul91
  • 20,072
  • 5
  • 36
  • 59