How to dynamically populate list items in React

Tags: , ,



I’m setting up an image slider with thumbnail slider using this plugin in React.js: http://flexslider.woothemes.com/thumbnail-slider.html

If I add the <li>s statically it works perfectly fine:

<div id="carousel" class="flexslider">
  <ul class="slides">
    <li><img src="slide1.jpg" /></li>
    <li><img src="slide2.jpg" /></li>
    <li><img src="slide3.jpg" /></li>
    <li><img src="slide4.jpg" /></li>
  </ul>
</div>

However if I try to load the content dynamically, the inline styles that are dynamically calculated and added by the plugin code won’t be added to both ul and li elements (i.e width: 210px; margin-right: 5px; float: left; display: block;)

This is how I do it:

render() {

  if(this.props.data){
    var projects = this.props.data.projects.map(function(projects){
    var projectImage = 'images/portfolio/'+projects.image;

    return <li key={projects.title}>
             <img alt={projects.title} src={projectImage} />
           </li>
    })
  }

  return (
    <section id="portfolio">
      <div id="carousel" class="flexslider">
        <ul class="slides">
          {projects}
        </ul>
      </div>
    </section>
  );
}

Answer

According to the link that you gave, the plugin requires initialization. Where are you doing your initialization?

I would recommend doing the initialization in the componentDidMount life cycle method. This is because when that code runs the <li> would have already been in DOM.



Source: stackoverflow