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:
(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)
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With