I have HTML documents that I fetch from my backend. Those documents consist of 2 kinds of tags and I want to render them dynamically. This is my source code
const Content = ({ slug }) => {
const [data, setData] = useState()
useScript("https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js");
useEffect(() => {
api.posts.read({ slug: slug }, { formats: ["html", "plaintext"] }).then((resp) => {
setData(resp)
})
}, [slug])
if (data) {
return (
<>
<SEO
title={data.title}
description={data.meta_description}
canonical_url={data.canonical_url}/>
<section className={'content'}>
<h4 className={'content-title'}>{data.title}</h4>
<div dangerouslySetInnerHTML={{ __html: data.html }}/>
</section>
</>
)
}
return <Section>
<CircularProgress style={{color: '#004D80'}}/>
<p>Loading</p>
</Section>
}
I tried these 2 but none of them works for my use case.
1 <script>
is rendered but not executed
<div dangerouslySetInnerHTML={{ __html: data.html }}/>
2
React: Script tag not working when inserted using dangerouslySetInnerHTML
This is not working for my case. What if I have tags like
<script src="https://gist.github.com/ogyalcin/66d0785998588ab50cf1908f8d43bb7b.js"></script>
in order to render a code block between two paragraphs? Besides, it is hard to handle if there are more attributes inside the tag.
2
Answers
Not an answer, just a bit of feedback FYI. I did an experiment inside browser. Seems like the script tag is rendered. However the code inside isn’t executed, not sure why.
May help:
Sample code from a create-react-app project.
There may also be a library for that:
dangerously-set-html-content
Sharing good article for more information:
Render dangerous content with React
Reference on innerHTML