Using Inkscape, I have generated svg files which contain paths that are identifiable by custom id. The objective is to implement a React component rendering one such svg file, styling one path given by id, and handing down onClick functionality to the styled path element. In my mind, there are two approaches.
First, one could load the svg file as a (mutable) data object and manipulate the path element directly. I do not want to do this.
Second, this could be achieved by layering the svg file in the background (ImageElement) with a styled svg element covering the original path element and another one providing event functionality. In order to "copy&paste" the given path from the background layer to the styled layer, I want to read the <d> attribute of the path from the svg file.
renderSvgElement() {
// from this.props.src get <d> attribute of path this.props.pathID
...
}
render () {
const ImageElement = React.forwardRef((props, ref) => <img
style={this.styles.img}
src={this.props.src}
ref={ref}
onClick={this.imageClick.bind(this)}
/>);
return (
<div
style={this.styles.container}
ref={(node) => this.container = node}
>
<ImageElement ref={this.imgRef} />
<svg
id="styled-layer"
ref={(node) => this.styledSvg = node}
style={this.styles.styledCanvas}
>
{this.renderSvgElement()}
</svg>
<svg
id="onClick-layer"
ref={(node) => this.onClickSvg = node}
style={this.styles.onClickCanvas}
>
{this.renderOnClickSvgElement()}
</svg>
</div>
);
I have tried variations of
path = document.querySelector("...").
contentDocument.querySelectorAll("path[path-id='...']")[0].getAttribute("d");
without success as the data object seems to be null on first render - at least the way I implemented it. Do I need to set the data object onComponentLoad / using React hooks, e.g. useEffect? Using the HTML DOM in such a way feels inelegant and not "reacty". Is there a better way?