1

so I have around 40 svgs in my frontend in seperate files, and I have an api route that gives me the name of the svg on request to I can import it, but I'm not quite sure how to dynamically import these svgs in react right now

I tried this but it means I can't change styles of svgs if I render them in img tag

export const renderIcon = ({ name, folder }) => {
  return <img src={`/${folder}/${name}.svg`} alt="" />;
};

is there a better way of doing this?

context:

basically name just returns the name of the svg and folder is only either "outline" or "filled", I was trying to find a way to return the svg from this file but i couldn't so i was trying the img instead.

A. Atiyah
  • 515
  • 1
  • 6
  • 16
  • please follow this link https://stackoverflow.com/questions/60562457/import-file-dynamically-by-variable-react-native – Muhammad Iqbal Jan 26 '21 at 06:34
  • Are you importing files bundled with your code or are you simply proving the source URL for an `img` tag? It seems you've the latter. You could preprocess and generate image source URLs and simply pass the `src` as a prop. Can you provide a bit more context? What is rendering `renderIcon` and what is `name` and `folder`? – Drew Reese Jan 26 '21 at 07:13
  • @DrewReese sorry, just added more context on the question – A. Atiyah Jan 26 '21 at 07:50
  • Where are the SVG files located in relation to your app? Could you try creating a [codesandbox](https://codesandbox.io/) for what you are trying to do? – Drew Reese Jan 26 '21 at 07:53
  • they're in the public folder of the frontend ( nextjs ) so basically if the svg is in /public/home.svg i can just add and it would work fine, I'm just not sure how to return it like that because the name of it comes dynamically from an api so I can't just import it in the top of the file – A. Atiyah Jan 26 '21 at 07:56

0 Answers0