react-optimized-image icon indicating copy to clipboard operation
react-optimized-image copied to clipboard

Pass image as prop throws error

Open mxmtsk opened this issue 3 years ago • 8 comments

I've created a Hero component that takes an image and title as props like so:

<Hero
  image={require('./images/test.jpg')} title="test"
/>

This is the component:

import React from 'react';
import Img from 'react-optimized-image';
import styles from './hero.module.scss';

const Hero: React.FC<IHeroProps> = ({ image, title }) => {
  return (
    <div className={styles.hero}>
      <Img src={image} className={styles.bg} />
      <h1>{title}</h1>
    </div>
  );
}

This throws the following error:

Error: Babel plugin 'react-optimized-image/plugin' not installed or this component could not be recognized by it.

However, when I use the image component directly like the following it works fine. Is this a limitation or a bug?

<Img src={require('./images/test.jpg')} className={styles.bg} />

mxmtsk avatar Aug 14 '20 13:08 mxmtsk

+1 I'm facing the same problem

devrasec avatar Aug 16 '20 23:08 devrasec

This is unfortunately a limitation of the current version, but I'll try to support custom wrapper components in a future version.

A possible workaround for now would be to have a component API similar to the one of next/link where you can pass the image as a child:

<Hero title="test">
	<Img src={require('./images/test.jpg')} />
</Hero>

But I'll update you once custom wrapper components are supported.

cyrilwanner avatar Aug 20 '20 14:08 cyrilwanner

I ran into this too.

Adding on to @cyrilwanner, it's a limitation of require. More info here.

Would the proposed Babel plugin address this? https://github.com/cyrilwanner/next-optimized-images/issues/120

allan2 avatar Aug 25 '20 02:08 allan2

Yes, this limitation comes from the babel plugin. I'll have to extend that so it correctly recognizes this use-case.

cyrilwanner avatar Aug 25 '20 09:08 cyrilwanner

@cyrilwanner any update on this?

avaleriani avatar Oct 20 '20 11:10 avaleriani

const image = ( <Img src={coverImage?.sourceUrl} className={cn('shadow-small', {'hover:shadow-medium transition-shadow duration-200': slug,})} /> )

breaks as predicted in earlier comments. I wish I could help figure this out but I don't know anything about babel.

jasperkooij avatar Oct 21 '20 15:10 jasperkooij

I'm using the canary version of https://github.com/cyrilwanner/next-optimized-images/ and I'm having this issue now

sahanatroam avatar Feb 15 '21 23:02 sahanatroam

any updates @cyrilwanner or instructions on how to correct this? Happy to help fix this.

sahanatroam avatar Feb 15 '21 23:02 sahanatroam