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
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
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 (Recommended).
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);
}
componentWillMount() {
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With