Modern JavaScript frameworks like React, Next.js, and Vue have changed how we handle assets. While importing images directly is the standard, there are many cases where using Base64 encoded images is more efficient.
In this guide, we'll show you how to implement Base64 images in the most popular frontend frameworks.
Using Base64 in React
In a standard React component, you can use a Base64 string just like any other variable.
const MyComponent = () => {
const base64Image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAE...";
return (
<div>
<img src={base64Image} alt="My Icon" />
</div>
);
};
Using Base64 in Next.js
Next.js's next/image component is powerful, but for small icons, you might want to bypass the optimization engine to reduce HTTP requests.
The "Blur Data URL" Trick
Next.js uses Base64 for its "blur-up" placeholder effect. You can provide a tiny Base64 version of your image to show while the high-res version loads.
import Image from 'next/image';
<Image
src="/large-photo.jpg"
placeholder="blur"
blurDataURL="data:image/jpeg;base64,/9j/4AAQSkZJRg..."
width={800}
height={600}
/>
Using Base64 in Vue
In Vue, you can bind a Base64 string to the src attribute using the v-bind or : syntax.
<template>
<img :src="base64String" alt="Vue Logo" />
</template>
<script setup>
const base64String = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAE...";
</script>
When to Use Base64 in Frameworks
- Dynamic Icons: If you're generating icons based on user input or state.
- Initial State: To ensure critical UI elements are visible before the main bundle or assets load.
- Server-Side Rendering (SSR): To include small images directly in the initial HTML payload.
Conclusion
Whether you're building a simple React app or a complex Next.js site, Base64 is a versatile tool for asset management. Just remember to compress your images before encoding to keep your bundles lean.
Need a string for your component? Convert your image here!