Bhaskararao Gummidi
Bhaskararao Gummidi

Reputation: 1635

Display images dynamically using map() in react not working

I want to display images in the sports array using map(). but not working

<div className="row">
   {this.state.sports.map(function(sport, index){
     return (
     <div className="col-md-3" key={index}>
       <h3 className="text-center">{this.state.sports.name}</h3>
       <img src={ require('./../assets/images/'+ {this.state.sports.name} +'.jpg') } width="300px" height="180px" />
       <button className="btn btn-info btn-sm" type="submit" onClick={this.join_in_sport} >JOIN</button>
     </div>
    )
  }.bind(this))}
</div> 

Upvotes: 0

Views: 661

Answers (3)

Chitambala Sikazwe
Chitambala Sikazwe

Reputation: 1

I was following the React beginners tutorial tried to call images dynamically by importing them as variables but this simply didn't work when trying to call them in another file (App.js) using the .map() function. Code below:

import katieImg from "../images/Katie.png"; import starImg from "../images/Katie.png";

export default [
  {
    img: { katieImg },
    star: { starImg },
    rating: "5.0",
    reviewCount: 6,
    location: "USA",
    title: "Life Lessons with Katie Zaferes",
    price: 136,
  },
];

So instead I had to get rid of the dynamically imported variables and put the images folder in the public folder. This worked. Code below:

export default [
  {
    img: "../images/Katie.png",
    star: "../images/Star.png",
    rating: "5.0",
    reviewCount: 6,
    location: "USA",
    title: "Life Lessons with Katie Zaferes",
    price: 136,
  },
];

Upvotes: 0

Sofiyan Ben_Z
Sofiyan Ben_Z

Reputation: 21

I have encountered the same problem, the image folder in src doesn't work. I moved the image folder to public and it works fine.

function App() {
  

 
  const moviesData = [
  
      name: "Terminator: Dark Fate",
      img: "./badboy3.jpg", //image in public folder
    },
  ];

  const movieList = moviesData.map((movie, i) => {
    return <Movie key={i} movieName={movie.name} movieImg={movie.img} />;
  });

  return (
    <div>
  
     {movieList}
     
    </div>
  );
}

export default App;

Upvotes: 0

Chris
Chris

Reputation: 59491

The problem seems to lie in how you are building the pathname for your image. Same for your <h3> tag.

src={ require('./../assets/images/'+ {this.state.sports.name} +'.jpg') }

If this.state.sports is an array, and not an object, then it can't possibly have a name key. I think you meant to print the current objects name for each iteration in your map().

So try:

<h3 className="text-center">{this.state.sports.name}</h3>
<img src={ require('./../assets/images/'+ {sport.name} +'.jpg') } width="300px" height="180px" />

This is assuming your array looks something like:

[
  {name: "foo"},
  {name: "bar"}
]

Upvotes: 2

Related Questions