Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

585
Views
using Base64 images in react.js

I am trying to use Base64 encoded images in my react app.

currently I load images from a folder and looks something like this:

<img className="..." src={imageFile}></img>

I want to use base64 encoded images, I think I can do this:

<img className="..." src={"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaH...."}></img>

the problem is that the base64 strings are huge, and for some reason I cant store them in my component. I tried putting them in a txt file and doing:

fs.readFile('image.txt', function(err, data){console.log(data);})

but I get tons of errors, including:

Uncaught TypeError: fs.readFile is not a function

among others.

any ideas how to store base64 strings in a separate file and load them into my component?

Thanks!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Decode the base64 using Buffer

let [imgSrc,setImgSrc] = useState('')
// 
let base64_to_imgsrc = Buffer.from(base64String, "base64").toString()
//add the string to the state
setImgSrc(base64_to_imgsrc)

and use it like this

  <img src={"data:image/jpeg;base64," + imgSrc} />
about 4 years ago · Juan Pablo Isaza Report

0

You can use a variable to store base64 data and export it.

// filename.js
const image = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaH....";

export default image;

// import
import image from 'filename';
about 4 years ago · Juan Pablo Isaza Report

0

There is three-way to do that, with FileReader and with fetch and the simplest way is to import it.

With Import

import Base64JSON from "./readme.json";

console.log(Base64JSON);

With FileReader

const readFile = async (json) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    const blob = new Blob([JSON.stringify(json)]);

    reader.onload = async (e) => resolve(JSON.parse(e.target.result));
    reader.readAsText(blob);
  });

With Fetch

const readFileUsingHttp = async (path) => {
  const json = await fetch(path);
  return json.json();
};

Here is the sandbox URL that shows all techniques.

Codesandbox: https://codesandbox.io/s/eager-golick-uvtcnh?file=/src/App.js

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!