0

I have next.js wrapper project around react ui library, which is included as npm package. Is there a way to use next/image for images optimization inside this React library?

I know that import next/image inside react project is not possible. So what is the approach to optimize images with next/image if images are inside another package?

Please, help! Thanks!

Mary Oleksiuk
  • 105
  • 2
  • 17

1 Answers1

0

Define Your own Image component and use it everywhere in your project, it might helpful!

import React from "react";

const Image = ({ src, ...props }) => {
 try {
  return React.createElement(require.resolve("next/image").default, {
   src: typeof src === "string" ? src : src.src,
   ...props
 });
 } catch {
  console.log("Not using Next.js");
  return React.createElement("img", { src, ...props });
 }
};

export default Image;

Use it like this (Please take this as an example)

import Image from "../utils/image";
import bg from "../assets/bg.jpg";

const Foo = () => <Image src={bg} height="640" width="959" />;

export default Foo;
Priyen Mehta
  • 1,096
  • 1
  • 5
  • 19
  • How can i pass this Image component into another React child components? I've tried to pass it down as a prop - `renderNextJSImage={(src, alt, layout, width, height) => {alt}}`, and then calling renderNextJSImage(); but i'm getting an error that 'is not a function' – Mary Oleksiuk Jul 28 '22 at 18:23
  • You have to import that component like same that i show you in above second part of answer. – Priyen Mehta Jul 29 '22 at 05:36
  • I can't import like that, because Image component should be passed to the npm package. So basically i have next wrapper and react ui library thats included as npm package. So i need to pass this component as a prop somehow – Mary Oleksiuk Jul 29 '22 at 06:34
  • Please try this once -> https://reactjs.org/docs/composition-vs-inheritance.html You can use props.children property. – Priyen Mehta Jul 29 '22 at 06:54