Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

588
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda