Michal Sládeček Michal Sládeček - 1 year ago 262
React JSX Question

React svg getTotalLength

I want to animate an SVG path using react (https://css-tricks.com/svg-line-animation-works/ , but in ReactJS).
To do that correctly, I need to know total length of a path, in JS you can do just path.getTotalLength(), how can I achieve the same when my path is created by JSX?

Answer Source

This is where React's refs come in handy see https://facebook.github.io/react/docs/more-about-refs.html

basically when you are creating the svg you would set a ref on the path and then you can access that ref (which is actually the element in the dom) and call the getTotalLength()

<svg><path ref="path"> </svg>

and then as long as the function you are using is a part of your react compnent you can just do

var path = this.refs.path;
var pathLength = path.getTotalLength()

if you are using es6, string refs are being deprecated and you would actually do something like

    <svg><path ref={(ref) => this.path = ref}> </svg>

either way works the latter is the preferred way and if you do the latter way you wouldn't call this.refs.path but just this.path to access the dom node

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download