0

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
arc
  • 1
  • 4
  • FYI: That `or die('****')` I removed is an invalid piece of code. I doubt it was the problem you are asking about so I removed it from the question – Dharman Feb 16 '21 at 14:22
  • sorry for that , i forgot to edit – arc Feb 16 '21 at 16:04

1 Answers1

0

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.