0

I don't understand why my loop render me only index[0] in my loop.... I have à state that's an array :

this.state = {
      days: ["Lundi","Mardi","Mercredi"]
    } 

And i want to render each day in my component:

render(){
    for (let i = 0; i < this.state.days.length; i++) {
      console.log(this.state.days[i]);
      return (

        <Text>{this.state.days[i]}</Text>

      );

Any ideas ??

E.D
  • 831
  • 3
  • 16
  • 33

5 Answers5

4

You break the loop with the return command, so it's enter only once to the loop

Roy Shmuli
  • 4,979
  • 1
  • 24
  • 38
1

Because you are returning within your for loop which breaks the loop

You are best to use map

render() {
    return (
      <div>
        { 
          array.map(day => {
            return (
              <p>{day}</p>
            );
          })
        }
      </div>
    );
  }
Stretch0
  • 8,362
  • 13
  • 71
  • 133
0

Your render method should be like this:

render(){
    return(
       <View>
         {this.state.days.map((item, index) => {
             <Text>{item}</Text>
           }
         )}
       </View>
    )

}
HSU WAI
  • 100
  • 9
0

.render must return a single root node. This way you're returning multiple nodes.

You need to do something like (wrap your content in a div)

  render() {
    return (
      <div>
        {
          this.state.days.map(d => <Text>{d}</Text>)
        }
      </div>
    );
  }
AdityaParab
  • 7,024
  • 3
  • 27
  • 40
0
 render() {
        this.state = {
            days: ["jan","feb","Mar"]
          } 
        return (
          <View style={styles.container}>
              { 
              this.state.days.map(d => <Text>{d}</Text>)
            }
            </View>
        )
 }
}
  • 1
    Please, can you extend your answer with more detailed explanation? This will be very useful for understanding. Thank you! – vezunchik Mar 29 '19 at 06:11