0

I have an array which has set of image names. I could print all the images by using console.log but unfortunately when I tried <img/> it didn't view images.

   for (let index = 0; index < array.length; index++) {
   const element = array[index];
   console.log(element)
     }

output of console.log(element)

DSC_0000038.jpg 
DSC_0000040.jpg 
DSC_0000039.jpg 
DSC_0000047.jpg 
DSC_0000045.jpg 
DSC_0000049.jpg 
DSC_0000042.jpg 
DSC_0000041.jpg

how to solve my problem?

8
  • Can you post the render method? Commented Feb 1, 2019 at 16:05
  • @DFord this is inside the render method Commented Feb 1, 2019 at 16:09
  • render: (record3) =>{ for (let index = 0; index < record3.split(",").length; index++) { const element = record3.split(",")[index]; console.log(element) } } Commented Feb 1, 2019 at 16:09
  • have you referred stackoverflow.com/questions/26054512/… Commented Feb 1, 2019 at 16:13
  • 5
    You shoud do something like: return array.map((image, index) => <img src={image} key={index} />). Note that you should not use index as a key, but it's just for the sake of this example, to show you that you should put key prop here. (It should be some unique id of the image). Without this prop, you'll get react error saying: Each child in array or iterator should have unique "key" prop. Commented Feb 1, 2019 at 16:24

1 Answer 1

1

Do something like this:

    import React from 'react'

    const myImages = [
    "DSC_0000038.jpg",
    "DSC_0000040.jpg", 
    "DSC_0000039.jpg", 
    "DSC_0000047.jpg", 
    "DSC_0000045.jpg", 
    "DSC_0000049.jpg", 
    "DSC_0000042.jpg", 
    "DSC_0000041.jpg"
    ]


    export default class Images extends React.Component{

      constructor(props){
        super(props)
        this.state = {
          path : '/img/'
        }
      }

      render(){

        const images = myImages.map(
          (image, index) => <img src={this.state.path + image} key={index} alt="image" />
        )

        return(

          <section>
            {images}
          </section>

        )
      }

    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.