Search code examples
javascriptreactjsimagesvgblob

Conver svg string to img source


I need to conver incoming string ' ' to img src attribute and pass it as prop to child component. How can I do that?

I tried this, but its not working.

`let blob = new Blob([data.payload], {type: 'image/svg+xml'});

      let url = URL.createObjectURL(blob);
      const image = document.createElement('img');
      image.addEventListener('load', () => URL.revokeObjectURL(url), {once: true});
      image.src = url;`

Solution

  • can you please try this code and lemme know if this works or not..

    let blob = new Blob([data.payload], {type: 'image/svg+xml'});
    
    let reader = new FileReader();
    reader.readAsDataURL(blob);
    
    reader.onloadend = () => {
      const image = new Image();
      image.src = reader.result;
    
      childComponent.propName = reader.result;
    }
    

    If you still facing issue let me know, i will help you ...