reactjs - Dynamically load images before render -
i've browsed lot of questions can't find correct answer this. have images
folder, , want display specific image in there. don't know name of image displayed, it's returned restful api along many other details on object i'm displaying.
i considered few alternatives that:
- load images no matter what, render ones need. found in few places, think it's pretty heavy, isn't it?
- use
webpack
require
file need on fly.
the second option seems best here. however, when do:
componentdidmount() { axios.get('http://url.to/my/restful/api') .then(res => { this.setstate(res.data); }); } render() { var pic = require(`../images/${this.state.picture}`) return (<img src={pic} alt="some name" />) );
react complains can't load undefined
, because starts rendering before axios call gets done. alternative display loader while call being done, or preventing rendering in general. question rather: what's best practice here? should have loader on every page loading dynamic data? suppose i'm missing something, why i'm reaching out. how that? lot.
try following:
class imageloader extends component { constructor() { super(); this.data = { data: null }; } componentdidmount() { axios.get("http://url.to/my/restful/api").then(res => { this.setstate({ data: res.data }); }); } render() { return this.state.data ? <img src={require(`../images/${this.state.data.picture}`)} alt="some name" /> : null; } }
Comments
Post a Comment