Search code examples
reactjsipfs

display image uploaded to ipfs dynamically in react frontend


I implemented the code below but when I click save it returns the ipfs hash but the uploaded image doesn't show on the frontpage. Please any help will be highly appreciated!

onSubmit = async (event) => {
    event.preventDefault();
    console.log('The file will be Submitted!');
    let data = this.state.buffer;
    console.log('Submit this: ', data);
    if (data){
      try{
        const postResponse = await ipfs.add(this.state.buffer) 
        console.log("postResponse", postResponse);
              
      } catch(e){
        console.log("Error: ", e)
      }
    } else{
      alert("No files submitted. Please try again.");
      console.log('ERROR: No data to submit');
    }
   
  }

Solution

  • You must use the returned CID hash to construct a valid image URL. Because the <img/> tag doesn't support ipfs:// URL scheme, you will have to relying on one of the HTTP gateways like ipfs.io or dweb.link as such:

    https://{gateway URL}/ipfs/{content ID}/{optional path to resource}
    

    So you could display the image using the <img/> tag like this:

    const Comp = () => {
      const [cid, setCid] = useState("");
    
      // logic to retrieve and set CID state
    
      return (
        <img src={`https://ipfs.io/ipfs/${cid}`} />
      );
    }