A
A
Alex Ozerov2020-12-16 19:18:18
React
Alex Ozerov, 2020-12-16 19:18:18

How to set the path to an image in a loop?

I have all the data stored in a separate state.js file, for example:

let state = {
    body: {
        home: {
            news:[
                {
                    image: './image/name.jpeg',
                    title: 'title '
                }
            ]
        }
    }
}

In state, info comes from a parser that collects info from another site.
I'm trying to render in a component:
{this.props.news.map((item,index) => {
    return(
        <div className={cl.event} key={index}>
                <img src={item.image} alt=""/>
                <div className={cl.title}>
                    <a href="/">{item.title}</a>
                </div>
        </div>
    )
})}

Of course, the images are not displayed.

If you do instead of image: './image/name.jpeg' => "image: logo" and import the image into the state, then everything will work. Example:
import logo from '../images/logo.jpg'

let state = {
    body: {
        home: {
            news:[
                {
                    image: logo,
                    title: 'title '
                }
            ]
        }
    }
}

This approach seems very strange to me. What is the correct way to display images in a loop?

PS I also tried this: But it's also not right
<img src={__dirname + item.image} alt=""/>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tigran Abrahamyan, 2020-12-16
@ozerovlife

This approach seems very strange to me.

Not weird, don't worry React uses this approach.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question