'How to use a local svg icon file in a React component?
I have an svg file with an eye icon. Something like below:
<svg width="18" height="18" viewBox="0 0 18 18" xmlns="http://www.w3.org/2000/svg">
<g fill="none" fill-rule="evenodd">
<path d="M9 3.627c-3.608 0-6.94 2.05-8.827 5.42L0 9.354l.173.308C2.059 13.032 5.392 15.082 9 15.082c3.608 0 6.941-2.05 8.827-5.419L18 9.355l-.173-.309C15.941 5.677 12.608 3.627 9 3.627zM9 4.9c2.947 0 5.7 1.588 7.401 4.257l.123.198-.123.197c-1.7 2.67-4.454 4.257-7.4 4.257-3.02 0-5.835-1.666-7.525-4.454C3.166 6.566 5.981 4.9 9 4.9zm0 1.273c-1.774 0-3.212 1.425-3.212 3.182S7.226 12.537 9 12.537c1.774 0 3.212-1.425 3.212-3.182S10.774 6.173 9 6.173zm0 1.273c1.065 0 1.927.854 1.927 1.909 0 1.054-.862 1.909-1.927 1.909a1.918 1.918 0 0 1-1.927-1.91c0-1.054.863-1.908 1.927-1.908z" fill="#6D727A" fill-rule="nonzero"/>
<path stroke="#6D727A" stroke-width="2" stroke-linecap="round" d="M2.246 15.881 15.68 2.447"/>
</g>
</svg>
Need to use in a component. Have done it as below:
import EyeIconOn from "../../../utils/resources/eye_icon_on.svg";
.
.
.
<table>
<tr>
<th>
<img
alt=""
onClick={() => {
setData(prevState => !prevState);
}}
className="dob-toggle"
src={EyeIconOn}
/>
</th>
</tr>
</table>
This seems to work fine in my local environment but does not show anything once deployed on actual environment. When I inspect element, this is how the img tag shows in the browser's Elements section:
<img alt="" class="dob-toggle" src="/static/media/eye_icon_on.9d23085a.svg">
Not sure why this invalid src path is shown here.
Solution 1:[1]
What about this
// eye_icon_on.js
const EyeIconOn = () => (<svg width="18" height="18" viewBox="0 0 18 18" xmlns="http://www.w3.org/2000/svg">
<g fill="none" fill-rule="evenodd">
<path d="M9 3.627c-3.608 0-6.94 2.05-8.827 5.42L0 9.354l.173.308C2.059 13.032 5.392 15.082 9 15.082c3.608 0 6.941-2.05 8.827-5.419L18 9.355l-.173-.309C15.941 5.677 12.608 3.627 9 3.627zM9 4.9c2.947 0 5.7 1.588 7.401 4.257l.123.198-.123.197c-1.7 2.67-4.454 4.257-7.4 4.257-3.02 0-5.835-1.666-7.525-4.454C3.166 6.566 5.981 4.9 9 4.9zm0 1.273c-1.774 0-3.212 1.425-3.212 3.182S7.226 12.537 9 12.537c1.774 0 3.212-1.425 3.212-3.182S10.774 6.173 9 6.173zm0 1.273c1.065 0 1.927.854 1.927 1.909 0 1.054-.862 1.909-1.927 1.909a1.918 1.918 0 0 1-1.927-1.91c0-1.054.863-1.908 1.927-1.908z" fill="#6D727A" fill-rule="nonzero"/>
<path stroke="#6D727A" stroke-width="2" stroke-linecap="round" d="M2.246 15.881 15.68 2.447"/>
</g>
</svg>);
export default EyeIconOn;
// In any of your component
import EyeIconOn from "../../../utils/resources/eye_icon_on.js";
.
.
.
<table>
<tr>
<th>
<EyeIconOn onClick={() => {setData(prevState => !prevState);}} />
</th>
</tr>
</table>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Paveloosha |
