So currently my react component creates svgs for the user, they can change from a light to a dark theme and the svg will update it's colors accordingly. I then want to allow the user to download the svg which I have working, but if the user changes the theme the svg won't update as I have the css inserted "inline". I want to create a custom function that adds the css to the svg but still allows the svg to be changed dynamically by theme after download.
function setCustomStyles(svg) {
const style = document.createElement("style");
style.innerHTML = Array.from(document.styleSheets)
.filter(
(styleSheet) =>
// Prevent CORS errors
!styleSheet.href || styleSheet.href.startsWith(document.location.origin)
)
.map((styleSheet) =>
Array.from(styleSheet.cssRules)
.map((rule) => rule.cssText)
.join(" ")
)
.join(" ");
svg.prepend(style);
}
Any ideas how I can do this?
Here is codesandbox example: https://codesandbox.io/s/silly-leftpad-nv163?file=/src/Main.js and try it out here: https://nv163.csb.app/
^ (change the css option to 'inline' to see working download example; svg is downloaded with styling applied but is immutable after. or change to 'custom' where styling can be changed after download but is not applied to the downloaded svg.)
Sidenote: it also seems to currently be inserting the whole css from the page, not specifically just the svg styling - any ideas how I could do this?