SVG tag -- creating SVG content on the fly

Suppose I’ve got a string like

let s = "<svg height=\"1000\" width=\"1000\">
 <rect width=\"300\" height=\"100\" style=\"fill:rgb(0,0,255);\" /> 

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


and have it appear. A year ago, this discussion suggested something like this:

@module external mySvg: string = "./img/my-nice.svg";

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


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.

Why not use JSX instead of a string?

let s =
  <svg height="1000" width="1000">
      style={ReactDOM.Style.make(~fill="rgb(0,0,255)", ())}

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);\" /> 
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.