Pedrum B.
Pedrum B.

Reputation: 21

Problem with loading local images added in object array in react

I made a #JS file called SliderImgs and put an array of objects in that which includes the properties of images of a slider:

const Images=[
    {
        src:'./files/new-banner-high.jpg',
        alt:'banner',
        order:'0'
    }
]
export default Images

Then I imported this array to a component and then passed that (the array) from props to another component called Slider

import React, { Component } from 'react'
import Images from './SliderImgs'
import Slider from './Slider'

 class Body extends Component {

  render() {
    return (
      <div>
        <div className="slider">
          <Slider pictures={Images}/>
        </div>
      </div>
    )
  }
}
export default Body

and finally tried to Print the Image on the screen using the map() method, but I got this error: Uncaught Error: Cannot find module './files/new-banner-high.jpg'

import React, { Component } from 'react'

 class Slider extends Component {
    constructor(props){
        super(props);
        this.state ={
          pictures:[]
        }
     }
     static getDerivedStateFromProps(props, state){
      return {pictures : props.pictures }
    ;
    }
  render() {
    return (
      <div className="slidercontainer">
          {this.state.pictures.map((picture, index)=> {
              return(
                  <img src={require(picture.src)} alt={picture.alt} key={index} />
              )
          })}
      </div>
    )
  }
}
export default Slider

Upvotes: 0

Views: 595

Answers (1)

Amila Senadheera
Amila Senadheera

Reputation: 13265

Normally images should be kept in the public folder.

  1. Move the files directory to the public folder.
  2. Change the array as below.
const Images=[
    {
        src:'/files/new-banner-high.jpg',
        alt:'banner',
        order:'0'
    }
]
  1. Change the img element like below.
<img src={picture.src} alt={picture.alt} key={index} />

Upvotes: 1

Related Questions