reactjs - how to replace image source in react? -


could please tell me how replace image source in react? .i setting src url img tag. if image not present on server want replace src url 1 http://punemirror.indiatimes.com/photo/55813567.cms

if image present on server fine .if not need change source url "http://punemirror.indiatimes.com/photo/55813567.cms "

here code https://codesandbox.io/s/korgkp3b8

i try that

imageexists(url, callback) {         var img = new image();         img.onload = function () {             callback(true);         };         img.onerror = function () {             callback(false);         };         img.src = url;     }       renderlist() {         const lis = this.items.map((item, key) => {             var src = "http://mumbaimirror.indiatimes.com/photo/" + item.id + ".cms";             const alt = "http://punemirror.indiatimes.com/photo/55813567.cms";              return (                 <li key={key}>                     <a><img src={src}/><span>{item.hl}</span></a>                 </li>             )         })         return (             <ul>                 {lis}             </ul>         )     }      render() {         return (             <div classname="list">                 {this.renderlist()}             </div>         )     } } 

check if image exists, use method , in component class :

componentwillmount() {   var url = "http://mumbaimirror.indiatimes.com/photo/" + item.id + ".cms";   const alt = "http://punemirror.indiatimes.com/photo/55813567.cms";   var src = this.imageexists(url) ? url : alt;   this.setstate({ src }); }  // added mentioned post function imageexists(image_url){     var http = new xmlhttprequest();     http.open('head', image_url, false);     http.send();     return http.status != 404; }  render() {     var src = this.state.src;     ... } 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -