reactjs render image dynamically - reactjs

To be clear:
<img src={require('../styles/myimage.jpg')} />
works fine. But I want to get this path dynamically as a string from api. In my parent component I fetch it and pass to child:
<img src={require(this.props.image)} />
In this case this.props.image is the same as '../styles/myimage.jpg'. But it does not work for me and throw this error "Uncaught (in promise) Error: Cannot find module "."
How can I fix it?
The directory tree is (I am trying to fetch myimage.jpg from image.js)enter image description here:
And webpack config: enter image description here

Do a simple test, move styles path with contains yours jpg files to same path of your component and try this path in props:
props.image = './styles/myimage.jpg'
then
<img src={require(this.props.image)} />

In addition to the comment what you can do is in your render method try this :
if (!this.props.image) return false;

Related

Can Dynamic and Constantly changing image URL work with Next/image

Can Next/Image use empty string variables for the src that'd get set later via an API?
I have an image url that I'd retrieve from an API. so the image src gets set after runtime. By default it's an empty string '' and then using SWR later it gets set to the full image url, eg https://i.imgur.com/Thgw1b.png
However, I get a build time error, Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {} despite having src already set. The same error occurs if src='' as well.
const myComponent = ({imageURL = ''}) => {
// imageURL starts off as '', then the parent updates that value to a proper image url when the API returns a url value.
return (
<>
// TODO: Fix build time error saying no src is set, despite being set to '' initially
<Image src={imageURL} alt='Dynamic Image' layout='responsive'/>
</>
);
}
Can Next/Image src images be set fully dynamically? Where it starts as an empty string then the src url gets populated later?
I've seen some answers suggesting useServerSide Props, but that won't work in my use case as the image url API gives a different image url every X hours (Hence using SWR). So just loading in once doesn't work.
Note that using <img> tags works perfectly. Initially there's no image, then after the image url gets set to the variable, the img tag loads the image in.
Try rendering the Image conditionally like so :
return (
<>
{imageUrl &&
<Image src={imageURL} alt='Dynamic Image' layout='responsive'/>
}
</>
)

How to pass image url array ["url1","url2"] to InitialState props in React Upload Gallery

I'm trying develop feature of adding/removing images in my system using React Upload Gallery. But I was unable to render the component with initial state. I'm looking help for this.
I have a predefined images in form of array. the state look like this:
images = ["imageURI1","imageURI2"]
The url is returning images and its working. So I wanted to assign this array into the component initialstate props so that the component will render with these images on first load but could find way to do it.
I've tried
initialState={[{source: this.state.images[0], name: 'image1'}]}
But seem not to be working.I received the error: TypeError: Cannot read property 'onCreated' of undefined
Here is the code snippet
<RUG
customRequest={handleImageUpload}
source={response => response}
onChange={handleImageChange}
initialState={[{source: this.state.images[0], name: 'image1'}]}
/>

Module image not found React Redux

I am having trouble locating the location of my images with react redux.
I am creating a react movie card that looks like this:
http://react-movie-cards.drminnaar.me/
My state is in the redux store.
My file structure is this.
the state is located at MovieList-reducer.js and I mapped it at MovieCard.js file.
why is it having an error like this:
×
←→1 of 6 errors on the page
Error: Cannot find module '../images/Kingsglaive_Final_Fantasy_XV.jpg'
▶ 32 stack frames were collapsed.
and have this in the terminal:
./src/Movies/MovieCard.js
Critical dependency: the request of a dependency is an expression
Please help me locate the file of the images.
you can find and clone my repo in https://github.com/bradrar/movie-cards and yarn start or npm start
I just need to locate the images and map it like so:
<img className="card-img-top" src={require(props.movie.imageUrl)} alt="" />
I know I am very close because I tried
<img className="card-img-top" src={require("../images/Ghost_In_The_Shell_2_0.jpg")} alt="" />
and it looks like this:
See my pull request here. Because webpack needs to know all your dependencies at build time, it's not possible to use require in a dynamic context. Use require.context() to build a context of all your images, and then reference them using that context.
First, change your references to use ./ instead (As because we're loading that folder into context, that essentially becomes the root ./):
{
"id": 100,
"title": "Kingsglaive",
...
"imageUrl": "./Kingsglaive_Final_Fantasy_XV.jpg"
},
And then in your movie card, create the context. (React will read through the folder at build time, and then give you the ability to access them using the context created):
const movieImages = require.context("../images/", true, /\.jpg$/);
const MovieCard = (props) => {
return (
...
<img className="card-img-top" src={movieImages(props.movie.imageUrl)} alt="" />
)
}

React.js Cant replace image source when image throws a 500 error

I have a React component which basically grabs an image and outputs it. However my issue is that I cant replace the image source when the image throws a 500. My page will return the image path (/images/icons/image.png) however that image itself does not exist, so it throws a 500 on me. This is fine, the issue is it wont trigger the onerror in the image so I cant replace the broken image with a fallback image. I've tried changing state, as well as an inline onerror function. None of those will work for me. WOuld anyone has a fix for this issue. This is what my component looks like:
const VerifiedLogo = ({ src, alt, isVerified }) => (
<div className={styles.logo}>
<img src={src ? src : '/images/icons/tournament-logo-placeholder.png'} alt={alt} onError="this.src='/images/icons/tournament-logo-placeholder.png'" />
<VerifiedBadge isVisible={isVerified} />
</div>
);
export default VerifiedLogo;
onError expects a function, in the constructor:
this.state = {
logoOk: false
}
in the render:
<img src={this.state.logoOk ? src : altLink} onError={()=>this.setState({logoOk: false})}/>

Can't pass relative img src route in React + Webpack

I can't dynamically pass relative img src route in React + Webpack with this.props.
This is a very simplified part of the parent component. It iterates some data list and generates ImgComponents passing props. Here is only tiny part of it:
return (
<div>
<ImgComponent srcProp={videolist.anotherImage.src} />
</div>
);
The ImgComponent has:
render() {
return (
<div>
<img src={`${this.props.srcProp}`} />
</div>
);
}
In console I get exactly the same route as i pass with this.props.srcProp, but it would not find the folder and the img there. As if webpack does not load the img.
Here is the console:
<img src="framework/assets/images/cover-bigbuckbunny.png" class="_2WcF9ZmcK-9bQX6jKk18Y_" data-reactid=".0.1.1:$comedy.0.0.$0.0.0.0">
No matter what route i indicate, the img is never found in the folder.
Here is the webpack config for png:
{ test: /\.png$/, loader: "url-loader?mimetype=image/png" }
BTW. It works fine if i require the file, like:
<img src={require ('framework/assets/images/cover-bigbuckbunny.png')} />
or indicate some remote route, like http://route.to.some.img
Seems like webpack does not load it. What should i do to dynamically load local img files by dynamically passing src with {this.props.src} ? As I can see, the loader loads img fine if i indicate the file with require. But this way i cannot do it dynamically, as require does not take variables.
What I managed to do is to require('../../assets/images/myFirst.img') in the object, containing the routs to the locally stored files:
in playlist.js
export default (
{
cartoons: [{
images: {
poster: require('../../assets/images/myFirst.png')
},
streams: [{
type: 'mp4',
url: 'http://media.w3.org/2010/05/bunny/movie.mp4'
}]
});
Then I work with this list as with any object:
import playlist from '../../playlist';
and iterate this object in a usual manner. The image will be there.
Webpack will not traverse your code to find and convert all possible references to files.
Consider following code:
<img src={'/foo/bar/baz.jpg'} />
It is your responsibility (perhaps using a build target) to ensure that baz.jpg is copied into the foo/bar directory under your web app root.

Resources