I have this svg component. I just want to use fallbacks if svg is missing. I have more than 50 SVG in the component. How can I do that? I'm using NextJS with Typescript.
CustomIcons.tsx
import React from "react";
const CustomIcons = (props: { name: string }) => {
const icons : any = {
FrameIcon: (
<svg
name="FrameIcon"
width="632"
height="330"
viewBox="0 0 632 330"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M460.923 -287.339L760.908 192.738C748.744 201.994 736.08 210.636 723.487 219.419C695.409 238.987 667.885 262.248 636.416 276.436C612.104 287.397 589.793 302.386 564.742 311.911C523.785 327.491 475.861 332.973 430.087 327.163C395.247 322.751 361.653 311.801 333.32 293.793C312.276 280.425 293.787 263.92 275.899 246.561C252.488 223.823 227.286 203.264 202.496 182.058C185.037 167.12 165.098 156.661 147.85 141.479C134.342 129.581 121.111 117.121 107.991 104.784C86.5556 84.6234 64.0287 65.4171 42.9997 44.8476C28.9062 31.0539 13.4654 16.1833 0.432617 0.407227L460.923 -287.339Z"
fill="#232323"
/>
</svg>
),
VectorIcon: (
<svg
name="VectorIcon"
width="632"
height="330"
viewBox="0 0 632 330"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M460.923 -287.339L760.908 192.738C748.744 201.994 736.08 210.636 723.487 219.419C69"
fill="#232323"
/>
</svg>
),
};
return <>{icons[props.name]}</>;
};
export default CustomIcons;
CodePudding user response:
return <>{icons[props.name] ? icons[props.name] : 'something else'}</>;
You can also use in
operator if you want
CodePudding user response:
You can use this. It checks if icon[props.name]
undefined
or not
import React from "react";
const CustomIcons = (props: { name: string }) => {
const icons : any = {
FrameIcon: (
<svg
name="FrameIcon"
width="632"
height="330"
viewBox="0 0 632 330"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M460.923 -287.339L760.908 192.738C748.744 201.994 736.08 210.636 723.487 219.419C695.409 238.987 667.885 262.248 636.416 276.436C612.104 287.397 589.793 302.386 564.742 311.911C523.785 327.491 475.861 332.973 430.087 327.163C395.247 322.751 361.653 311.801 333.32 293.793C312.276 280.425 293.787 263.92 275.899 246.561C252.488 223.823 227.286 203.264 202.496 182.058C185.037 167.12 165.098 156.661 147.85 141.479C134.342 129.581 121.111 117.121 107.991 104.784C86.5556 84.6234 64.0287 65.4171 42.9997 44.8476C28.9062 31.0539 13.4654 16.1833 0.432617 0.407227L460.923 -287.339Z"
fill="#232323"
/>
</svg>
),
VectorIcon: (
<svg
name="VectorIcon"
width="632"
height="330"
viewBox="0 0 632 330"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M460.923 -287.339L760.908 192.738C748.744 201.994 736.08 210.636 723.487 219.419C69"
fill="#232323"
/>
</svg>
),
};
return <>{icons[props.name] ? icons[props.name] : <p>Does not exist</p>}</>;
};
export default CustomIcons;