NextJs - Render an Image using url from a componet that dynamically create a img component using base 64 string

15 Views Asked by At

NextJS - v13+ RouteType - Pages

I have a use case to generate & load image on run time To load image dynamically using dynamic page component that contain img element with path as base64 string

I need to save the template with the mentioned src path in image tag.

But at time of rendering on Nextjs it must show a image in template

Expected Result: I should see the image in template component with image page url & image must be visible on screen.

Issue: I am not able to load image in template tag. Also if I route & go to Image Page I am able to see the image in that component

Please provide a solution for if any. P.N : I tried the same with next/image but same issue persists.

Please find the implementation that I have done on my end Template Component

const Template = () => {
  return (
    <div>
      <h1>Welcome to Next.js!</h1>
      <img src="/images?name=blue_ocean.jpg" alt="Blue Ocean" />
    </div>
  );
};

export default Template;

I Defined a dynamic route in pages directory to handle the image requests pages/images/[name].js

import ImageComponent from '../../components/ImageComponent';

const ImagePage = ({ name }) => {
  return <ImageComponent imageName={name} />;
};

export default ImagePage;

export async function getServerSideProps({ params }) {
  const { name } = params;
  return { props: { name } };
}

Finally the Image Component which is generating the img from base 64 string got from API

import { useEffect, useState } from 'react';

const ImageComponent = ({ imageName }) => {
  const [base64String, setBase64String] = useState('');

  useEffect(() => {
    const fetchImage = async () => {
      try {
        const response = await fetch(`https://your-api-url/api/images/${imageName}`);
        const data = await response.json();
        setBase64String(data.base64String);
      } catch (error) {
        console.error('Error fetching image:', error);
      }
    };

    fetchImage();
  }, [imageName]);

  return <img src={`data:image/png;base64,${base64String}`} alt="Base64 Image" />;
};

export default ImageComponent;
0

There are 0 best solutions below