let s = "<svg height=\"1000\" width=\"1000\">
<rect width=\"300\" height=\"100\" style=\"fill:rgb(0,0,255);\" />
</svg>"
corresponding to a blue rectangle, and I’d like to display that blue rectangle in the middle of some larger html document. I’d like to do something like
...
<div>
{React.string(s)}
</div>
...
and have it appear. A year ago, this discussion suggested something like this:
@module external mySvg: string = "./img/my-nice.svg";
@react.component
let make = () => {
<img src=mySvg/>
}
which would be great if my svg was saved in a file somewhere, but it’s not – it’s actually more complicated, and I’m creating it on the fly. Is there some way to make this (or something like it) work? I’d be quite happy to trim off the starting and ending <svg ...> and </svg> parts if that’d make it easier. For instance, if I could do something like
…
React.string(t)
…
where t is the trimmed version of s, that’d be great.
Also: I never need to edit/mess with the SVG contents – I just want to periodically replace it entirely when some button is pressed, for instance.
let s =
<svg height="1000" width="1000">
<rect
width="300"
height="100"
style={ReactDOM.Style.make(~fill="rgb(0,0,255)", ())}
/>
</svg>
You can also render a string as HTML with dangerouslySetInnerHTML, but you probably want to use JSX instead of this.
let s = "<svg height=\"1000\" width=\"1000\">
<rect width=\"300\" height=\"100\" style=\"fill:rgb(0,0,255);\" />
</svg>"
let e = <div dangerouslySetInnerHTML={"__html": s} />
Thanks for the ideas. I happen to have already created the string, which I’ll eventually drop into a file (or a textbox for the user to copy), and I was looking for a way to do an easy preview of the SVG. So that why I don’t use JSX instead of a string.
Perhaps I’ll try the “dangerously” thing, because it looks like an easy way to get the result I want until I can understand how I might properly use an <svg> tag.
Ah, I see. If you have a string that you want to render as HTML, then dangerouslySetInnerHTML is the only way to do that in React. There’s nothing special about <svg> tags; they work just like rendering any HTML in React.