Uploading local images to React.js

I installed React using the application create-react-app. It is installed normally, but I'm trying to upload an image to one of my components ( Header.js, file path :) src/components/common/Header.js, but it does not load. Here is my code:

import React from 'react'; 

export default () => {
  var logo1 = (
    <img 
      //src="https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-goose.jpg"
      src={'/src/images/logo.png'}
      alt="Canvas Logo"
    />
  );
  return (
    <div id="header-wrap">
      <div className="container clearfix">
        <div id="primary-menu-trigger">
          <i className="icon-reorder"></i>
        </div>

        <div id="logo">
          <a href="/" className="standard-logo" data-dark-logo='/images/logo-dark.png'>{logo1}</a>
          <a href="/" className="retina-logo" data-dark-logo='/images/logo-dark@2x.png'>
            <img src='/var/www/html/react-demo/src/images/logo@2x.png' alt="Canvas Logo" />
          </a>
        </div>
      </div>
    </div>
  );
} 

If I write the image path as src={require('./src/images/logo.png')}in my variable logo1, this will throw an error:

Failed to compile.

A mistake in. /src/Components/common/Header.js

Module not found: ./ src / images / logo.png in / var / www / html / wistful / src / Components / common

Please help me solve this. Let me know what I'm doing wrong here.

+16
source share
4 answers

React App, .
, .

, , :

  • :

    // Assuming logo.png is in the same folder as JS file
    import logo from './logo.png';
    
    // ...later
    <img src={logo} alt="logo" />
    

, . , .

, , , .

  1. :

    // Assuming logo.png is in public/ folder of your project
    <img src={process.env.PUBLIC_URL + '/logo.png'} alt="logo" />
    

, , , , . , .

, !

+38

local relative URL . public . images . .

enter image description here

+5

, :

import myimage from './...' // wherever is it.

img src:

<img src={myimage}...>

: https://facebook.imtqy.com/react-native/docs/image.html

+2

Instead of using img src = "", try creating and setting the background-image as the image you want.

It works for me right now.

0
source

Source: https://habr.com/ru/post/1677835/


All Articles