1
   {
       storedfiles.map(item => {
                        // return <li key={item.id}>{item.imagepath}</li>
                        return (
                            <div>
                            <li key={item.id}>{item.imagepath}</li>
                                <img src={require(`${item.imagepath}`)} style={{width:"100px" , height:'100px'}} alt='pics' />
                                </div>
                        )
                    })
                }

i am getting image path from the database which is { item.imagepath }, you can see in the img tag. it is not working , it says couldn't find that module. "...path" but when i put that hard corded path on the place of variable , it shows an img . mean with hard corded value it's working and with variable it's not. How could i solve it?

Asim Hafeez
  • 59
  • 3
  • 11
  • Does this answer your question? [React Native: require() with Dynamic String?](https://stackoverflow.com/questions/44991669/react-native-require-with-dynamic-string) – Anurag Srivastava Apr 05 '20 at 18:09
  • nop, they just have images in their static folder which they try to catch by using require and storing them in another module in different variables and then accessing them, but in my case i cant do that... my images paths are coming from db when be n number... – Asim Hafeez Apr 05 '20 at 18:20
  • What is the scenario of file path saving? 1. Full path? 2. Relative file path ? 3. Only file name + extension ? – OO7 Apr 05 '20 at 19:12
  • full path ... from C:/ to onward... – Asim Hafeez Apr 05 '20 at 19:16

2 Answers2

2

Thanks to all of you... this problem is solved.

{

                storedfiles.map(item => {
                    return (
                        <div>
                        <li key={item.id}>{item.imagepath}</li>
                            <img src={process.env.PUBLIC_URL , `${item.imagepath}`} style={{width:"100px" , height:'100px'}} alt='pics' />
                            </div>
                    )
                })
            }

store images in the public directory of reactjs or nextjs project and access them like this through env variable. It works <3 also check it if you need more specific answer https://create-react-app.dev/docs/adding-images-fonts-and-files/

Asim Hafeez
  • 59
  • 3
  • 11
1
  1. First, require is being used to load a module, which is why its return value is typically assigned to a variable: var misc = require('./misc');, and prop src from tag img should receive URL, not a module.

  2. There is a reason why we define a project root folder and not just taking from any other path outside project root folder. Better to put your image inside your project root folder or use CDN to store that image and put the fullpath like: https://cdn.com/path/to/image in prop src in tag img.

Hope that helps!

Darryl RN
  • 7,432
  • 4
  • 26
  • 46