netzwerg netzwerg - 2 months ago 25
React JSX Question

React & SVG: HTML inside foreignobject not rendered

I am embedding HTML inside SVG via

foreignobject
:



var SvgWithForeignObject = React.createClass({
render: function() {
return(
<svg>
<foreignobject><div>Hello From SVG</div></foreignobject>
</svg>
)
}
});

ReactDOM.render( < SvgWithForeignObject / > ,
document.getElementById('container')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>





The "Hello From SVG" string is not rendered. However, I can make a minor whitespace edit in Chrome or FF and then it becomes visible:

enter image description here

(Note: The screen recording is from an example where I use React via Scala.js, but the behavior is exactly the same with plain React)

Answer

SVG is case sensitive and the element you want to use is called foreignObject. Note the upper cased O.

Also, you must set a width and height attribute on this element.

Finally, don't forget to set xmlns="http://www.w3.org/1999/xhtml" on your root HTML element.

var SvgWithForeignObject = React.createClass({
  render: function() {
    return(
      <svg>
        <foreignObject width="400" height="400"><div xmlns="http://www.w3.org/1999/xhtml">Hello From SVG</div></foreignObject>
      </svg>
    )
  }
});

ReactDOM.render( < SvgWithForeignObject / > ,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="container">
  <!-- This element's contents will be replaced with your component. -->
</div>