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.

16 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?”

Leave a Comment