'Uncaught Error: Cannot find module 'file:/home/agemiro/backend-gerenciador/uploads/imagemteste.png'

I'm using React JS and I'm having trouble accessing an image that comes from a state/variable. If I put the url inside the require in the html img it works but when it comes from outside it doesn't work at all. I wish someone would clarify this because it's been four days since I've been trying to find out. Important: This url I'm using comes from outside the React application

 const [sideDishesImage, setSideDishesImage] = useState([
    {
        fileName: "",
        id: "",
        message: "",
        sideId: "",
        url: "file:/home/agemiro/backend-gerenciador/uploads/imagemteste.png"
        
    }
]); 

<img {require(`${sideDishesImage[0].url}`)} alt="image" />


Solution 1:[1]

You have two ways to reference an asset in a create-react-app app:

  • path to the asset, the asset has to be placed in the public folder, and you can reference it like:

    const url = "/images/myImage.png"  // myImage.png must be inside "public/images"
    <img src={url} alt="alt" />
    
  • Load the asset through webpack:

    import img from "path/to/the/asset.png" // This can be outside of public folder but must be inside the /src folder
    <img src={img} alt="alt" />
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1