site-library/temp/jsx.md
2025-03-08 21:04:49 +01:00

2.1 KiB

Here's an example of an Astro component that renders JSX from a string:

---
// JSXFromString.astro

// Import the necessary runtime for JSX parsing
import * as runtime from 'react/jsx-runtime';

interface Props {
  jsxString: string;
}

const { jsxString } = Astro.props;


// Convert the string to JSX
const jsx = evaluateJSX(jsxString);
---

{/* Render the evaluated JSX */}
{jsx ? <Fragment set:html={jsx} /> : <p>Failed to render JSX</p>}

Usage example:

---
// Example.astro
import JSXFromString from './JSXFromString.astro';

const jsxString = `
  <div className="container">
    <h1>Hello from JSX string!</h1>
    <p>This is rendered from a string</p>
  </div>
`;
---

<JSXFromString jsxString={jsxString} />

Alternative simpler approach using set:html:

---
// SimpleJSXFromString.astro

interface Props {
  htmlString: string;
}

const { htmlString } = Astro.props;
---

<div set:html={htmlString} />

Usage:

---
// Example.astro
import SimpleJSXFromString from './SimpleJSXFromString.astro';

const htmlString = `
  <div class="container">
    <h1>Hello from HTML string!</h1>
    <p>This is rendered from a string</p>
  </div>
`;
---
<SimpleJSXFromString htmlString={htmlString} />

Important notes:

  1. Be careful with security when rendering strings as JSX/HTML. Only use trusted content to avoid XSS attacks.

  2. The first approach using JSX evaluation is more complex but gives you more control over the rendering process.

  3. The second approach using set:html is simpler but only works with HTML strings, not JSX expressions.

  4. Add proper error handling and validation depending on your needs.

  5. You might want to add sanitization:

---
import sanitizeHtml from 'sanitize-html';

interface Props {
  htmlString: string;
}

const { htmlString } = Astro.props;

// Sanitize the HTML string
const sanitizedHtml = sanitizeHtml(htmlString, {
  allowedTags: ['div', 'h1', 'p', 'span'], // specify allowed tags
  allowedAttributes: {} // specify allowed attributes
});
---

<div set:html={sanitizedHtml} />

Choose the approach that best fits your needs and security requirements.