This repository has been archived on 2025-12-24. You can view files and clone it, but cannot push or open issues or pull requests.
site-template/temp/jsx.md
2025-03-07 14:59:06 +01:00

108 lines
2.1 KiB
Markdown

Here's an example of an Astro component that renders JSX from a string:
```astro
---
// 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:
```astro
---
// 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`:
```astro
---
// SimpleJSXFromString.astro
interface Props {
htmlString: string;
}
const { htmlString } = Astro.props;
---
<div set:html={htmlString} />
```
Usage:
```astro
---
// 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:
```astro
---
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.