Reputation: 734
I am writing a react app that creates an SVG from text input.
It provides a few text inputs and has a context provider and a component SVGOutput. The JSX is constructed like this:
return(
<>
<SomeInputFields/>
<ContextProvider value{{
someVariables,
forTheContext
}}>
<TextOptions/>
<SVGOutput/>
</ContextProvider>
</>
);
The SVGOutput component has a JSX like this
return (
<svg
version="1.1"
xmlns="http://www.w3.org/2000/svg"
>
{
svgData.map((svgPath, i) =>
<path
key={i}
fill={svgPath.fill}
d={svgPath.d}
transform={svgPath.transform}
/>
)
}
</svg>
);
I tried using renderToString
from react-dom/server
to get the SVG but it does not quite work, the SVG is empty, the paths that are into the DOM while using the apps don't get rendered into the String.
renderToString(
<ContextProvider value{{
someVariables,
forTheContext
}}>
<SVGOutput/>
</ContextProvider>
</>
);
With some text on the SVG calling this function gives me a string without the path elements.
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" style="height:[object Object];width:800px" preserveAspectRatio="xMinYMin meet" width="20" height="20"></svg>
I am assuming this is because renderToString does not get the updated component but the component as it looks on first render?
Is there a possibility to get the current state of <SVGOutput>
as a string?
The only other option I can imagine is tying an external function to the window object and in that function have "vanilla javascript" select the svg element and get it as a string...? But is there an option using that within react?
Upvotes: 0
Views: 709
Reputation: 1129
One way to solve this, is to use a ref
in the <svg>
tag, and then get the string from ref.current.innerHTML
.
Upvotes: 1