How to load images in React?

How to load images in React?

Images can be loaded through two types of links/URLs:

  1. External links (i.e. a URL pointing to a resource on the web)
  2. Internal or local links (i.e. a URL pointing to a resource within your website/domain)
  • External links can be used as it is.
  • Example:
    <img src="https://reactjs.org/logo-og.png" alt="logo" />
    
  • Internal or local links have to be used a little differently in React.
  • They cannot be directly used as it is.
  • Example:

    <img src="../assets/imgs/logo512.png" alt="logo" /> 
    <!-- This will not display the image -->
    
  • So how do we display images from these kinds of links?

    Method 1:

  • Import the image at the top and then use the variable in the src of your img tag.

    import image1 from "../../assets/images/image1.png";
    <img src={image1} alt="food" />
    

    Method 2:

  • Use require to load the image and then use the variable in the src of your img tag.
  • Note: Depending on the react-scripts version, we need to chain the require keyword with a default keyword.

    var image1 = require("../../assets/images/image1.png"); 
    <img src={image1.default} alt="food" />
    <!-- OR DIRECTLY -->
    <img src={require("../../assets/images/image1.png").default} alt="food" />
    

    NOTE:

  • This code will look for the image in the public directory.
    <img src={process.env.PUBLIC_URL + 'logo512.png'} alt="logo" />
    <!-- OR simply  -->
    <img src="logo512.png" alt="logo" />