Wednesday, 7 June 2017

Rendering dynamic images in React while iterating through a list with map

I'm having some difficulty trying to insert dynamic images into "cards" that I want to render. I'm loading the necessary information for the components from Firebase-database (including the relative path to the image) and, during the callback function, pushing each created component into an array that I'm rendering to the page.

The issue is that <img src={fly.image)/> doesn't work, despite the correct path being loaded in (I've checked) and the images appropriately imported. Here's the code:

import React, { Component } from 'react';
import * as firebase from 'firebase';
import './Flies.css'
import Adams from './images/adams.jpg'
import Bugger from './images/bugger.jpg'
import Caddis from './images/caddis.jpg'
import Hendrickson from './images/hendrickson.jpg'



class Flies extends Component {

  constructor(props){
    super(props);
    this.state = {
      flies: []
    }
  }


  componentDidMount(){
    var allFlies = firebase.database().ref('flies');
      allFlies.on('value', function(snapshot){
          var myObj = snapshot.val();
          var array = Object.keys(myObj).map(key => myObj[key])


          //FORMAT THE DATA FOR THE FLYCARDS
          const flyItems = array.map((fly, index) =>
              <div className="flyCard" key={index} id={fly.id}>
                <h3>{fly.name}</h3>
                <img src={fly.image}/>
                <div className="details">
                  <p>Hook size: {fly.hooksize}</p>
                  <p>Thread: {fly.thread}</p>
                  <p>Hackle: {fly.hackle}</p>
                  <p>Link: <a href={fly.youtube}>Youtube</a></p>
                </div>
              </div>
            );

          //ASSIGN FLYCARDS TO STATE FOR DISPLAY
          this.setState({flies:flyItems})
       }.bind(this))
  }

  render() {
    return (
      <div className="flies">
        <h1>Fly test</h1>
        <div>
          {this.state.flies}
        </div>
      </div>
    );
  }
}

export default Flies;

That will render images with broken links. However, will work, because it's referencing the import directly. The problem is that I'm not sure how to make the {Adams} part dynamic, which is why I'm loading the path (./images/adams.jpg) from Firebase. I believe that the relevant path changes when Webpack compiles everything, which would explain why it's not working. Still, I'm not sure what the proper fix is here, even after reading up on other people having similar problems for several hours now. Any help would be appreciated!!



via yoursweater

No comments:

Post a Comment