I am importing local images then exporting them to be rendered with .map() but they aren't loading

Viewed 29

I want to make an Image slider for a web app I am working on, but the images don't seem to be loading / displaying when I use local images, if I add the source as a link, it works fine.

Here are the 3 components I have so far:

Component 1: The one that "renders" everything

import React from 'react'
import '../styles/MyWork.css'

import { MyWorkTemplate } from './MyWorkTemplate'

function MyWork() {
  return (
    <section>
      <div>
          <MyWorkTemplate/>
      </div>
    </section>
  )
}

export default MyWork

Component 2: Where my images are created

import React, {useState} from 'react'
import { ImageSliderInfo } from './ImageSliderInfo'
import '../styles/MyWorkTemplate.css'

import {FaArrowCircleRight, FaArrowCircleLeft} from 'react-icons/fa'


export const MyWorkTemplate = () => {

    const length = ImageSliderInfo.length;

    const [current, setCurrent] = useState(0);
    
    const nextImage = () => {
        setCurrent(current === length - 1 ? 0 : current + 1)
    }

    const previousImage = () => {
        setCurrent(current === 0 ? length - 1 : current - 1 )
    }

    if(!Array.isArray(ImageSliderInfo) || length <= 0){
        return null
    }

  return (
    <div className='imageSliderContainer'>
        <FaArrowCircleRight className='rightArrow' onClick={nextImage}/>
        <FaArrowCircleLeft className='leftArrow' onClick={previousImage}/>
        {ImageSliderInfo.map((image, index, key) => {
            return (
                <div key={key.imageKey} className={index === current ? 'image active' : 'image'} >
                    {index === current && (<img src={image.image} alt='travel' className='imageSrc'/>)}
                </div>
            )
        })}
    </div>
)
}

Finally, Component 3: Where the info of the images are stored

import img1 from '../assets/myworkphotos/img1.jpg'
import img1 from '../assets/myworkphotos/img2.jpg'


export const ImageSliderInfo = [
    {
      imageKey : '1546768292',
      image: {img1}
    },
    {
      imageKey : '2414950165',
      image: {img2}
    }
]

This is what I have so far, and as mentioned above, whenever I use a link as the image: value in the 3rd component, it works fine.

I know it's not any of the paths the issue. I also tried using: require({img1}), which worked for like a second before throwing so many errors and warnings to the point I had to restart the entire project (I have no idea what happened).

I've searched online and tried a few things but ultimately haven't found the answer to anything yet.

1 Answers

You could use

  const ImageSliderInfo = [
{
  imageKey: "1546768292",
  image: `${img1}`,
  alt: "Firts Pic"
},
{
  imageKey: "2414950165",
  image: `${img2}`,
  alt: "Second Pic"
}

];

and the CodeSand is here ==> LINK

Related