react-optimized-image
react-optimized-image copied to clipboard
Pass image as prop throws error
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} />
+1 I'm facing the same problem
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.
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
Yes, this limitation comes from the babel plugin. I'll have to extend that so it correctly recognizes this use-case.
@cyrilwanner any update on this?
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.
I'm using the canary version of https://github.com/cyrilwanner/next-optimized-images/ and I'm having this issue now
any updates @cyrilwanner or instructions on how to correct this? Happy to help fix this.