0

I created an SVG rectangle by code, that I'm trying to render in React. I tried different things including dangerouslySetInnerHTML, without success.

In below example, 'return t' works, 'return svgRectElement' doesn't.

How can I return the svg generated by svgRectElement? Thanks!

public render() {
    let svgRectElement: SVGRectElement = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
    svgRectElement.setAttributeNS(null, 'width', "300");
    svgRectElement.setAttributeNS(null, 'height', "300");
    svgRectElement.setAttributeNS(null, 'id', "myrect");        

    var t: JSX.Element = <rect width="300" height="100" id="myrect"></rect>;

    return t;
}
Greg Forel
  • 2,199
  • 6
  • 25
  • 46
  • 1
    Don't create DOM nodes in your render function. That's not how react works. If you need to bypass React create it in the componentDidMount function and attach it to something returned by your render function. Further reading https://github.com/ryanflorence/react-training/blob/gh-pages/lessons/05-wrapping-dom-libs.md – Andy Ray Oct 02 '16 at 00:35
  • Thanks Andy. As I told Scarysize below, what I want to do is generate my svg with SnapSvg, with dynamic attributes (x, y, etc.), and then render with React. I guess both you and him suggested the same technical solution. – Greg Forel Oct 02 '16 at 17:16

1 Answers1

0

I don't know how you create your SVG element and how what variables are necessary for the creation, but the straight forward way would be to just wrap it into a component:

const MySvg = props => <svg xmlns="http://www.w3.org/2000/svg">...</svg>;

If it has some dynamic properties (e.g. styling, classnames etc.), you can calculate those from the given props.

Scarysize
  • 4,131
  • 25
  • 37
  • Thanks both for your answers (@AndyRay). Ultimately, I have a graph of nodes that I want to display using the SnapSvg library, and yes, x, y, width, height and more will be dynamic properties. So, I intend to create my svg components (each node) using Snap, not writing the svg itself, e.g: Snap.rect(x, y, ...). Would you still approach this the way you described? – Greg Forel Oct 02 '16 at 15:36
  • Haven't used SnapSvg myself, but from the docs I would do the following: Have component render a empty `` tag. Attach a `ref` to it and then do the SnapSvg stuff in `componentDidMount/willReceiveProps`. Still using react props to update the component. – Scarysize Oct 02 '16 at 16:43
  • Thanks for the recommendation. I'll try that and come back with my results – Greg Forel Oct 02 '16 at 16:48