Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Images not loading in React

not able to display the image getting an error as not found but i have provided the full path for it. I don't know where i am going wrong.

class App extends React.Component {

   render() {
      return (
               <div>
                  <h1> hello</h1>    
                <img src="/home/priyanka/Finalproject/src/components/3.jpg" alt="cannot display"/>    
              </div>    
           );
         }
  }

export default App;
like image 891
Abhilash Muttalli Avatar asked Jan 31 '17 10:01

Abhilash Muttalli


2 Answers

If you are using webpack, you need to use require while mentioning the src for img tag. Also the url must be relative to the component.

class App extends React.Component {

   render() {
      return (
         <div>
  <h1> hello</h1>

<img src={require("./home/priyanka/Finalproject/src/components/3.jpg")} alt="cannot display"/>

         </div>

      );
   }
}

export default App;

If you are not using webpack then simplly wrapping the src value within {} will work

class App extends React.Component {

   render() {
      return (
         <div>
  <h1> hello</h1>

<img src={"./home/priyanka/Finalproject/src/components/3.jpg"} alt="cannot display"/>

         </div>

      );
   }
}

export default App;
like image 121
Shubham Khatri Avatar answered Sep 24 '22 03:09

Shubham Khatri


You can read Why can't I do <img src="C:/localfile.jpg">? to know why it is not working.

If you use following method

import img from "/home/priyanka/Finalproject/src/components/3.jpg";
class App extends React.Component {



   render() {
      return (
         <div>
  <h1> hello</h1>

<img src={img} alt="cannot display"/>

         </div>

      );
   }
}

export default App;
like image 39
mary_jane Avatar answered Sep 23 '22 03:09

mary_jane