Home > Blockchain >  How to render SVG component using props?
How to render SVG component using props?

Time:06-19

I'm trying to render an SVG using props of a function. Any help on how to achieve this?

Here is the code:

import React from "react";
import Camera from "../icons/Camera.svg";

export default function Button(props) {
  console.log(props.icon);
  return (
    <button
      type="button"
      className="mx-auto mb-2.5 flex items-center gap-2 rounded-lg border border-gray-300 px-3.5 py-2 text-sm font-medium text-gray-700 drop-shadow-sm"
    >
      {props.icon} /* SVG ICONS GOES HERE*/
      {props.label}
    </button>
  );
}

CodePudding user response:

Could try:

import React from "react";
import Camera from "../icons/Camera.svg";

export default function Button({icon, label}) {
  return (
    <button
      type="button"
      className="mx-auto mb-2.5 flex items-center gap-2 rounded-lg border border-gray-300 px-3.5 py-2 text-sm font-medium text-gray-700 drop-shadow-sm"
    >
      {icon && <img src={Camera} alt={label} />}
    </button>
  );
}

CodePudding user response:

Here is how you can add an Icon https://codesandbox.io/s/react-playground-forked-x4vsge?file=/index.js

However, a few things when you are creating these components.

  1. If the Icons source is an API (CMS) then you should have some predefined icons and should have your icons library build and pass just icon names.
  2. If you have very limited icons build SVG icons as components and use them

CodePudding user response:

When you use your Button component just use the SVG as a JSX

import Camera from "../icons/Camera.svg";

export default function App() {
  return <Button icon={<Camera />} label="Click Me" />;
}
  • Related