skip to Main Content

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


  1. 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.

    DOMPurify sanitizes HTML and prevents XSS attacks. You can feed DOMPurify with string full of dirty HTML and it will return a string (unless configured otherwise) with clean HTML.

    // Assuming `response.text` contains the dirty HTML
    const clean = DOMPurify.sanitize(response.text);
    

    Use the clean variable for safe HTML content.

    Login or Signup to reply.
  2. 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

    import React from 'react';
    import DOMPurify from 'dompurify';
    
    const sanitizeHTML = (html: string) => {
      return { __html: DOMPurify.sanitize(html) };
    };
    
    const HTMLRenderer = ({ htmlContent }: { htmlContent: string }) => {
      return <div dangerouslySetInnerHTML={sanitizeHTML(htmlContent)} />;
    };
    
    export default HTMLRenderer;
    Now you can use this HTMLRenderer component to render HTML content safely:
    
    jsx
    Copy code
    import React from 'react';
    import HTMLRenderer from './HTMLRenderer';
    
    const MyComponent = () => {
      const htmlContent = '<p>This is <b>HTML</b> content.</p>';
    
      return (
        <div>
          <h1>Render HTML Safely</h1>
          <HTMLRenderer htmlContent={htmlContent} />
        </div>
      );
    };
    
    export default MyComponent;

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search