In the comment section of my forum-like website, users can attach files in a post.
When making comments, users can edit using Rich Text Editor and quote a file attached in the post;
When users make a comment quoting a file, the data stored in backend database after the comment is submitted will be a string that contains html tags, example:
const commentContent = "
<p><br></p>
<p>This is a comment</p>
<blockquote>
BJFC123_003.jpeg
</blockquote>
<p>Hi John, this is the file that I mentioned about</p>
<p>please click to download the file</p>
<p><br></p>
"
when other users read the post, the comment is fetched and the above text is loaded like the below way to convert pure string into actual html for displaying:
<div
className="ql-editor"
dangerouslySetInnerHTML={{ __html: commentContent }}
{...otherProps}
/>
Now, instead of this simple scenario, I need to make a twist:
when loading the comment, instead of loading html as described in the original text, I need to add onclick
event to all blockquote
tags.
So the actual loaded elements in the DOM should be:
<p><br></p>
<p>This is a comment</p>
<blockquote onclick={myCustomMethod(filename)}>
BJFC123_003.jpeg
</blockquote>
<p>Hi John, this is the file that I mentioned about</p>
<p>please click to download the file</p>
<p><br></p>
Here,
myCustomMethod()
is a function defined in the comments component
filename
will be equal to "BJFC123_003.jpeg"
It is easy to extract the file name from the string commentContent
, but how to make such a modification when converting from string to actual html?