1

I've mapped my redux store to props, but I'm now having trouble rendering it dynamically. I've also tried projectCards(){...} syntax, but that was a total shot in the dark. My console logs are showing the objects coming through the way I want them. I also tried using projects.map, but I don't think I want to put the return values in a new array. I just want more <Card/> items on the page, dynamically rendered. Where have I gone wrong? Any help would be appreciated.

Class Projects extends...
.
.
.
 projectCards = () => {
  if ( this.props.projects.length !== 0 ) {
   this.props.projects.forEach((project) => {
     return <Card fluid color='green' header={project.name} />
  })
 }
}

 render(){
  return(
    <Container>
      <br/>
      <Card.Group>
        <Card fluid color='green' header='Option 1' />
        <Card fluid color='blue' header='Option 2' />
        <Card fluid color='red' header='Option 3' />
        { this.projectCards() }
      </Card.Group>
    </Container>
  )
 }
}
Oleksandr Fediashov
  • 4,315
  • 1
  • 24
  • 42
user4396386
  • 423
  • 8
  • 15
  • Use `.map()` instead of `.forEach()`. Some past, helpful StackOverflow answers on this: https://stackoverflow.com/questions/47442462/reactjs-map-works-but-foreach-doesnt, https://stackoverflow.com/questions/42460357/react-js-component-map-works-foreach-doesnt – Andy Taton Oct 02 '18 at 02:03

1 Answers1

1

Try this:

projectCards = () => {
  if ( this.props.projects.length !== 0 ) {
    return this.props.projects.map( project => 
       <Card fluid color='green' header={project.name} />
    )
  }
}
You Nguyen
  • 9,961
  • 4
  • 26
  • 52
  • It worked! So I wanted to return an array of ``s? – user4396386 Oct 02 '18 at 02:59
  • Got it! However, do you think that it's possible to make the function return value more than one time? After returning the first `Card component`, it's done! The other Card components won't have a chance to come to life. Btw, why don't you want to `return an array of s` – You Nguyen Oct 02 '18 at 03:04
  • That's a good point. Not the first time I've tried multiple return statements in the same function today! – user4396386 Oct 02 '18 at 03:13
  • I can't edit it, but there's a curly missing in your post. Thanks for your help. – user4396386 Oct 02 '18 at 03:16