I want to take a image path from the database and display it in a react component, I am using require(),(Error: Cannot find module) occurs?

import React from 'react'
import { Component } from 'react';
import axios from 'axios';
const url="http://localhost:80/form/api/hello.php"
class Studio extends Component{
    state={
        users:[]
    }
    componentDidMount(){
        axios.get(url)
        .then(result=>{
            this.setState({user:result.data})
            
        });
    }
    render(){
        let{user}=this.state;
        return(
        <div>
        {
            user && user.map(users=>{
               
              return(
                 <div key={users.id}>
                     
                     <img width="270" height="160" alt="" src={require(users.name)} draggable="false"/>
                    
                     
                 </div>
                 )
                })
             }
                
             </div>)
}
}
export default Studio;

Here the ‘name’ is the column name of the image path.
The error does not occur when I give the same value of name as
string parameter in the require() function.

This is the php file that gives the data.

<?php 
header("Access-Control-Allow-Origin: *");
$rest_json = file_get_contents('php://input',true);
$_POST = json_decode($rest_json, true);
$user ='root';
$password="";
$db="event";
$data=[];
$d= new mysqli('localhost',$user,$password,$db);
$sql = "SELECT * from upload";
$result = mysqli_query($d, $sql);
while($row = mysqli_fetch_assoc($result)){
  $data[] = $row;
}  

echo json_encode($data);
$d->close();
?>

The uploads is the file in src where the images are saved.

2 thoughts on “I want to take a image path from the database and display it in a react component, I am using require(),(Error: Cannot find module) occurs?”

  1. according to this question, require() doesn’t accept variable. It takes only string. If you can retrieve image from the backend directly.You can just put the path into the src parameter.

    const picturePath = "http://localhost:80/img/ABC_123.jpg";
    <img src={picturePath}></img>
    

    Or you may retrieve the picture as base64 or other string type then convert it to base64, prepend header and put the string into the src parameter. Like this answer.

    Reply

Leave a Comment