How can I store an svg in MongoDB?

528 Views Asked by At

I am working on a MERN app that needs to show an svg map of golfcourses. There are many golfcourses and they each have their own svg maps. So I want to store the svg with the rest of the specific golfcourse data in mongodb. Then fetch it in react and import it into my react code. Is this possible? How do I render the svg on react after retrieving it?

I have only ever imported an svg from local storing.

And one other thing is that I need to apply css to the svg for interaction. So I cant do

1

There are 1 best solutions below

0
Ivan Shumilin On

You can store an svg as a string in your database. And then render it with dangerouslySetInnerHTML:

import React from "react";

const svg = `<svg
xmlns="http://www.w3.org/2000/svg"
className="w-6 h-6"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
>
<path
  strokeLinecap="round"
  strokeLinejoin="round"
  d="M8 16l2.879-2.879m0 0a3 3 0 104.243-4.242 3 3 0 00-4.243 4.242zM21 12a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>`;

export default function App() {
  return <div dangerouslySetInnerHTML={{ __html: svg }} />;
}

Working example