Reputation: 1813
This is quite a specific issue I'm having so I am hoping someone can help me out.
I am generating a QR code via SVG method in Bacon QR Code generator (Laravel) and it generates something along the lines of this:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="200" height="200" viewBox="0 0 200 200">
<rect x="0" y="0" width="200" height="200" fill="#fefefe"/>
<g transform="scale(4.082)"><g transform="translate(4,4)">
<path fill-rule="evenodd" d="DATA GOES HERE" fill="#000000" />
</g></g>
Where it says 'DATA GOES HERE' is the generated data that makes up the QR code. I used a call in my React component to the back end to generate this, then I tried putting it into a state which I would then display in the block I created, but it just literally renders this as plain text. After some testing I saw that I can add the data to the state and then implement it in the path element like so:
<path fill-rule="evenodd" d={ this.state.qrCodeData } fill="#000000" />
However, getting just that data is proving difficult. Basically what I'm asking is, is there a way to pluck out the attribute 'd' from the 'path' element in React, but from the above SVG code that's generated from the back end?
Thank you in advance.
Upvotes: 0
Views: 58
Reputation: 389
You can make either option work. To render the svg as html and not plaintext, you would use dangerouslySetInnerHTML
. You should only do this if you trust the SVG. Otherwise, to grab just the d
, you could use a regex. It's definitely safe, and depending on what your data is could work perfectly well. If your SVG plaintext is stored as svgString
, you could do something like: svgString[svgString.search(/g="[^"]*"/g)];
. It's a little icky, but at least doesn't open you up to XSS attacks.
Upvotes: 1