最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - unable to display svg's from local folder using React js - Stack Overflow

programmeradmin1浏览0评论

what i need : I am trying to display svg from external folder and that folder contains some 50 files and

public folder
  |-images
        -| 50 svgs

in app.js

i am trying to display the image

import React from 'react';
import './App.css';
import svgs from "../public/svgfolder/0.svg"
class App extends React.Component{

   render(){
     return(
       <div>
         <img src={svgs} alt="test"></img>
       </div>
     )
   }
}

export default App;

i am getting below error

Module not found: You attempted to import ../public/svgfolder/0.svg which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.

here i need 3 things

  1. How can we display 50 svgs dynamically in react ?
  2. some people are suggesting to make change in the web pack so is it right approach i mean will it work in production also ?
  3. do we have to use public folder or any other folder ?
  4. React support svg's ?

Note : if i call svg through url <img src={".svg"}/>,

it is working and if the same using local file it is not

and if u put the svg single file src folder then a single file can be able to display

what i need : I am trying to display svg from external folder and that folder contains some 50 files and

public folder
  |-images
        -| 50 svgs

in app.js

i am trying to display the image

import React from 'react';
import './App.css';
import svgs from "../public/svgfolder/0.svg"
class App extends React.Component{

   render(){
     return(
       <div>
         <img src={svgs} alt="test"></img>
       </div>
     )
   }
}

export default App;

i am getting below error

Module not found: You attempted to import ../public/svgfolder/0.svg which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.

here i need 3 things

  1. How can we display 50 svgs dynamically in react ?
  2. some people are suggesting to make change in the web pack so is it right approach i mean will it work in production also ?
  3. do we have to use public folder or any other folder ?
  4. React support svg's ?

Note : if i call svg through url <img src={"https://s.cdpn.io/3/kiwi.svg"}/>,

it is working and if the same using local file it is not

and if u put the svg single file src folder then a single file can be able to display

Share Improve this question edited May 22, 2019 at 16:19 Madpop asked May 22, 2019 at 15:55 MadpopMadpop 7254 gold badges29 silver badges63 bronze badges 2
  • Have you looked into SVG middleware? Have you looked into whether or not webpack can pile SVGs without a loader? Have you looked into inline SVG as React Components? – cullanrocks Commented May 22, 2019 at 16:01
  • Just so you know, if you put an SVG in an IMG tag it will not behave like an SVG. It will behave like in image. See my answer below for a better solution. – cullanrocks Commented May 22, 2019 at 16:07
Add a ment  | 

4 Answers 4

Reset to default 3

React does not give access to content outside of src directory to be used in React code.

Possible solutions may be:

  • Move your svg inside src directory (Remended).

  • Use Public folder and access it like this. (Using Public Folder)

.

// Using Public Folder
import React from 'react';
import './App.css';
class App extends React.Component{
  render(){
    const svgs = ["0.svg", "23.svg",...];
    return(
       <div>
         {svgs.map(svg => 
            <img src={`${process.env.PUBLIC_URL}/svgfolder/${svg}`} alt="test"></img>
         }
       </div>
     )
   }
}

export default App;

I too have the same scenario where i tried this approach and it worked u can try

import React from 'react';
import './App.css';

var images = [];

class App extends React.Component {

     importAll(r) {
      return r.keys().map(r);
    }


  ponentWillMount() {
    images = this.importAll(require.context('../public/public/svgfolder/', false, /\.(png|jpe?g|svg)$/));
  }
  render(){
    return(
      <div>
        <div>
         {images.map((image, index) => <div> <p>{index + 1}</p> <img  key={index} src={image} alt="info"></img> </div>  )}
       </div>
      </div>
    )
  }
}

export default App;

Instead of loading SVGs how you are currently doing it, I would remend inline SVG as React Components. This way you can control the styling with props and state too as well as many other useful capabilities.

Example:

import React from 'react';
import ReactDOM from 'react-dom'

const GithubSVG = (props) => {
  const { backFill, className, mainFill } = props.props;
  return(
    <svg
      className={className}
      height='512'
      id='Layer_1'
      version='1.1'
      viewBox='0 0 512 512'
      width='512'
    >
      <defs id='defs'/>
      <g id='g'>
        <rect
          height='512'
          id='rect'
          style={{
            fill: backFill,
            fillOpacity: 1,
            fillRule: 'nonzero',
            stroke: 'none'
          }}
          width='512'
          x='0'
          y='0'
        />
        <path
          d='a bunch of random numbers'
          id='svg'
          style={{fill: mainFill}}
        />
      </g>
    </svg>
  )
}

export default GithubSVG;

You can now import that ponent anywhere.

If you are using Webpack, it is better to use svg-url-loader for webpack & package them with your deployments.

Add below in your webpack.config

 module: {
    rules: [
      {
        test: /\.svg/,
        use: { loader: 'svg-url-loader', options: {} },
      }
   ]
}

app.css

.zero {
  background: url('../public/svgfolder/0.svg') no-repeat;
}

app.js

<i className="zero" />
发布评论

评论列表(0)

  1. 暂无评论