ReactJS and images in public folder

后端 未结 7 1567
北恋
北恋 2020-11-30 01:15

Im new in ReactJS and I want to import images in a component. These images are inside of the public folder and I do not know how to access the folder from the react componen

相关标签:
7条回答
  • 2020-11-30 01:25

    We know React is SPA. Everything is rendered from the root component by expanding to appropriate HTML from JSX.

    So it does not matter where you want to use the images. Best practice is to use an absolute path (with reference to public). Do not worry about relative paths.

    In your case, this should work everywhere:

    "./images/logofooter.png"

    0 讨论(0)
  • 2020-11-30 01:28

    the react docs explain this nicely in the documentation, you have to use process.env.PUBLIC_URL with images placed in the public folder. See here for more info

    return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;
    
    0 讨论(0)
  • 2020-11-30 01:33

    To reference images in public there are two ways I know how to do it straight forward. One is like above from Homam Bahrani.

    using

        <img src={process.env.PUBLIC_URL + '/yourPathHere.jpg'} /> 
    

    And since this works you really don't need anything else but, this also works...

        <img src={window.location.origin + '/yourPathHere.jpg'} />
    
    0 讨论(0)
  • 2020-11-30 01:36

    You Could also use this.. it works assuming 'yourimage.jpg' is in your public folder.

    <img src={'./yourimage.jpg'}/>
    
    0 讨论(0)
  • 2020-11-30 01:38

    1- It's good if you use webpack for configurations but you can simply use image path and react will find out that that it's in public directory.

    <img src="/image.jpg">
    

    2- If you want to use webpack which is a standard practice in React. You can use these rules in your webpack.config.dev.js file.

    module: {
      rules: [
        {
          test: /\.(jpe?g|gif|png|svg)$/i,
          use: [
            {
              loader: 'url-loader',
              options: {
                limit: 10000
              }
            }
          ]
        }
      ],
    },
    

    then you can import image file in react components and use it.

    import image from '../../public/images/logofooter.png'
    
    <img src={image}/>
    
    0 讨论(0)
  • 2020-11-30 01:42

    You don't need any webpack configuration for this..

    In your component just give image path. By default react will know its in public directory.

    <img src="/image.jpg" alt="image" />
    
    0 讨论(0)
提交回复
热议问题