Home > OS >  Is it possible to parse SVG from string in Next.js as a component?
Is it possible to parse SVG from string in Next.js as a component?

Time:07-17

We are creating a headless CMS in which users can modify sections of their website they can upload images, modify texts and ordinary stuff of each headless CMS

However, we also want to give them the ability to upload SVG for some sections.

For example, the "services" section can contain some services that user offers, and for each service we want him to be able to upload an SVG that is relevant to that service.

This means that inside our next.js site, we get SVG from API and we have it as a string

Is it possible for us to parse it into a component and use it as a component?

Pseudo-code:


const json = await callApi()

const { svgIcon } = json

const svgComponent = magicParser(svgIcon)

<SvgComponent className="fill-red-400" />

CodePudding user response:

I believe you can use the dangerouslySetInnerHTML attribute in a div for example. You won't need to use a "magic parser", thus.

As per your code, this would look like this, I suppose:

const json = await callApi()
const { svgIcon } = json

return (
  <div dangerouslySetInnerHTML={{ __html: svgIcon }}></div>
)

With this, you don't even have to create a component.

CodePudding user response:

You should use dangerouslySetInnerHTML

const json = await callApi()

const { svgIcon } = json

const SvgComponent = ({ className }) => <div
    className={className}
    dangerouslySetInnerHTML={{ __html: svgIcon }}
/>
  • Related