4

i'm trying to load a list of wallpapers from local storage that i already post them and saved their paths in mongoDB.

So i'm trying to loop through the array of paths and use each path as src in each img tag

the main.js component :

import React, { Component } from 'react'

export default class Main extends Component {
    state = {
        data : []
    }
    componentDidMount(){

        fetch('http://localhost:5000/').then(res => res.json())
        .then(data=> this.setState({data}))

    }
    render() {

        console.log(this.state.data)

        return (
            <div>
                <h1>Main</h1>
                {this.state.data ? this.state.data.map(img => 
(<div key={img._id}>{img ? <img src={require(`${img.img.path}`)} 
alt={img.img.name}/>:<span>deleted</span>}</div>)): 
<h3>loading</h3>}
            </div>
        )
    }
}

the server code :

  server.get('/', (req, res)=>{
        Wallpaper.find({}, (err, result)=>{
            if(err) {
                res.json({msg: err})
            }else{
                res.json(result)
            }
        })
    })

it should return the images in the uploads folder in the react app but it returns this error:

Error: Cannot find module '/home/ahdy/Workspace/Wally/wallcraft/public/uploads/ak47456193147469824_n.jpg'
2
  • Why the require() call? If those images are in some folder on the server, just the src directly to their URL. Commented Jul 18, 2019 at 13:43
  • this.state.data ? will be true anyways, use this.state.data.length ? Commented Jul 18, 2019 at 13:59

1 Answer 1

1

This

<img src={require(`${img.img.path}`)}

should be

<img src={`/uploads/${img.img.path}`}

no need of require here

NB: put correct path there

Sign up to request clarification or add additional context in comments.

1 Comment

thanks i fixed it like you mentioned but instead of img.path i used img.name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.