I am working to create a blog website. The user will use a text editor to create a new blog ( which I am using is Ckeditor5). What I want is for the user can insert the images anywhere he or she wants. I successfully uploaded the post to the server when I checked the JSON, it returned something like this.
{
"id": 12,
"title": "bài viết số 12",
"text": "<p>`12131441411âfafafa</p><p><img src="null"></p>",
"time_created": "2024-03-03T14:34:34.090+00:00",
"time_updated": null,
"post_background_img": null,
"views": null,
"user": {
"id": 1,
"username": "john_doe",
"email": "[email protected]",
"password": "$2a$12$VbU4xpQPAwrtnpPXZWB/0.J7pY6py/E04k2n5i23cL5hom.Zi85A6",
"avatar": "http://example.com/avatar.jpg",
"ban": false
},
"comments": []
}
it inserts the tag into the text,
so how can I render it back to normal HTML in reactjs, I have searched on Google, and I can use dangerous HTML,
but it is very unsafe. Is there any way I can achieve what I want, and the second thing is when I post the image to the server it returns null
this is the code snippet I used to upload
async function handleSubmit(e) {
e.preventDefault();
// Create the blog post object
const newBlog = {
title,
slug,
text: content,
};
// Post the blog data to the server
const userID = 1; // Replace with actual userID
const response = await fetch(
`https://englishforum.zeabur.app/api/v1/posts/user/${userID}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newBlog),
}
);
if (response.ok) {
console.log("Blog post created successfully:", newBlog);
// You might want to redirect the user or show a success message here
} else {
console.error("Failed to create blog post");
// Handle error scenario
}
}
2
Answers
Use DOMPurify to sanitize dangerous HTML and prevent XSS attacks. DOMPurify allows you to sanitize a string full of dirty HTML, returning clean HTML. This is useful for ensuring the safety of dynamically generated content on your website. Learn more about it on GitHub.
Use the
clean
variable for safe HTML content.For rendering HTML code in React components in versions earlier than React 18, you can use the dangerouslySetInnerHTML attribute. Here’s how you can do it:
First, install dompurify and @types/dompurify if you haven’t already:
bash
Copy code
npm install dompurify @types/dompurify
Then, you can create a utility function to sanitize and render HTML:
jsx
Copy code
This way, you can render HTML content safely in React components for versions earlier than React 18. Make sure to always sanitize user-generated or dynamic HTML content to prevent XSS attacks.