Unable To Display Svg's From Local Folder Using React Js
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 dis
Solution 1:
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 FolderimportReactfrom'react';
import'./App.css';
classAppextendsReact.Component{
render(){
const svgs = ["0.svg", "23.svg",...];
return(
<div>
{svgs.map(svg =>
<imgsrc={`${process.env.PUBLIC_URL}/svgfolder/${svg}`} alt="test"></img>
}
</div>
)
}
}
exportdefaultApp;
Solution 2:
I too have the same scenario where i tried this approach and it worked u can try
importReactfrom'react';
import'./App.css';
var images = [];
classAppextendsReact.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><imgkey={index}src={image}alt="info"></img></div> )}
</div></div>
)
}
}
exportdefaultApp;
Solution 3:
Instead of loading SVGs how you are currently doing it, I would recommend 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:
importReactfrom'react';
importReactDOM from'react-dom'constGithubSVG = (props) => {
const { backFill, className, mainFill } = props.props;
return(
<svgclassName={className}height='512'id='Layer_1'version='1.1'viewBox='0 0 512 512'width='512'
><defsid='defs'/><gid='g'><rectheight='512'id='rect'style={{fill:backFill,
fillOpacity:1,
fillRule: 'nonzero',
stroke: 'none'
}}
width='512'x='0'y='0'
/><pathd='a bunch of random numbers'id='svg'style={{fill:mainFill}}
/></g></svg>
)
}
exportdefaultGithubSVG;
You can now import that component anywhere.
Solution 4:
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
<iclassName="zero" />
Post a Comment for "Unable To Display Svg's From Local Folder Using React Js"