Ayesha
Ayesha

Reputation: 221

How to render local images in React js

I just want to render my local images which I have saved locally in my 'images' Folder. I Have imported the whole images folder. In my state I have added the Src properties ( Please see the image below). SomeWhere I am making very stupid mistake, I have tried to google and see some of the Youtube videos. But Nothing getting the answer I want. When i run the Code I dont see any image there. Any Help Will be Appreciated! Thanks

import * as React from 'react';
import "../setStateFunctionExample/images/";
class ImageSlider extends React.Component {
    state= {
        images: [ {
            id: 1, src: "./images/image1.jpg", alt: "fruitLogo"
        }
        ,
        {
            id: 2, src: "./images/image2.jpg", alt: "fruitLogo1"
        }
        ,
        {
            id: 2, src: "./images/image3.jpg", alt: "fruitLogo2"
        }
        ],
        idx: 0
    }
    ;
    render() {
        return( <div> <h3>setState() example</h3> <img src= {
            this.state.images[0].src
        }
        alt= {
            this.state.images[0].alt
        }
        /> </div>)
    }
}

export default ImageSlider;

Upvotes: 0

Views: 264

Answers (1)

demkovych
demkovych

Reputation: 8817

You can import images dynamically with require:

state= {
    images: [ {
        id: 1, src: "image1.jpg", alt: "fruitLogo"
    }
    ,
    {
        id: 2, src: "image2.jpg", alt: "fruitLogo1"
    }
    ,
    {
        id: 2, src: "image3.jpg", alt: "fruitLogo2"
    }
    ],
    idx: 0
}

....
{this.state.images.map(item => <img src={require(`./images/${item.src}`)} />)}

Upvotes: 2

Related Questions