Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React & SVG: HTML inside foreignobject not rendered

Tags:

reactjs

svg

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)

like image 701
Rahel Lüthy Avatar asked Sep 15 '16 07:09

Rahel Lüthy


1 Answers

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>
like image 154
Kaiido Avatar answered Nov 07 '22 15:11

Kaiido