0

The code below causes a react-dom error:

import React from "react";

const svg = `<svg><line x1=null y1="10" x2="100" y2="200" /></svg>`;

export default function App() {
  return <div dangerouslySetInnerHTML={{ __html: svg }} />;
}

Error: attribute x1: Expected length, "null".

How can I handle this error gracefully?

I expected that adding an error boundary would catch the problem, but it made no difference

import React from "react";

const svg = `<svg><line x1=null y1="10" x2="100" y2="200" /></svg>`;

let withErrorBoundary;
try {
  withErrorBoundary = <div dangerouslySetInnerHTML={{ __html: svg }} />;
} catch {
  <div>oops! content could not be rendered</div>;
}
export default function App() {
  return <div dangerouslySetInnerHTML={{ __html: svg }} />;
}

EDIT: Dump of error as requested by @DennisWash

Dump of error

user1283776
  • 19,640
  • 49
  • 136
  • 276
  • Are you sure it gives an error? Try to replicate it https://codesandbox.io/s/brave-sea-bik04?file=/index.js – Dennis Vash Jun 11 '20 at 07:38
  • Why exposing security breach, rather than [simply](https://create-react-app.dev/docs/adding-images-fonts-and-files/#adding-svgs) doing something, like `import {ReactComponent as MyLine} from './line.svg'`? – Yevhen Horbunkov Jun 11 '20 at 07:42
  • @YevgenGorbunkov: I haven't found anything that works for me yet, but I hope that I will. I tried rendering the SVG as a background (https://medium.com/@ians/rendering-svgs-as-images-directly-in-react-a26615c45770), but then the browser did not render the SVG at all if it encountered any syntax problem, in which case I prefer the behavior I have with injected SVG where the browser does a best effort to render the content. I have the SVG as a string (not a file) and don't use webpack, so am unsure how to achieve your suggestion. I will say that at least I sanitize the SVG before inserting. – user1283776 Jun 11 '20 at 08:25
  • @DennisVash I added a screen dump of the error to the question – user1283776 Jun 11 '20 at 08:29
  • You can use svg elements in JSX without having to dangerously set them by the way. Doing `
    ...
    ` will mostly work. This can also allow for IDE warnings when something is wrong with the elements
    – apokryfos Jun 11 '20 at 08:34
  • @apokryfos: The SVG string is created at runtime, so I can't use that option. – user1283776 Jun 11 '20 at 10:10
  • Does this answer your question? [Check if HTML snippet is valid with Javascript](https://stackoverflow.com/questions/10026626/check-if-html-snippet-is-valid-with-javascript) – apokryfos Jun 11 '20 at 10:35
  • @apokryfos: That might be the best solution. I would prefer to be able to catch the error from react-dom. But maybe there isn't any mechanism for that. – user1283776 Jun 11 '20 at 10:37

0 Answers0