Getting Started with React: Creating Your Own Blog App - Part 6

React for Beginners: Crafting a Custom Blog Application

Getting Started with React: Creating Your Own Blog App - Part 6

Introduction

In this article of our React blog series, we will implement a blog view page that displays our blog for users to read. Up to this point, we have covered all aspects of our blog app. Creating a page to showcase our blog content will be incredibly straightforward.

If you'd like to do it on your own, I would be happy to know that you've learned a lot from this React series and can implement this feature independently. Before you begin writing the code, let me inform you that we need to use the dompurify package to display our blog content.

A quick note before we begin: We are building a blog app, and this blog series focuses on learning React through hands-on projects. This will be a basic app without any high-level concepts in React, but in the future, I will introduce some advanced concepts to enhance your understanding.

If you are new to React, I recommend reading my previous blogposts, in which I explain and demonstrate how to install React with Vite, along with other project setup steps, CRUD operations, profile and search features. I strongly encourage you to read those blog posts before proceeding with this one.

Prerequisites

What will we learn in this blog?

In this blog post, we will explore the process of displaying react-draft-wysiwyg content in a web browser. Contrary to what might be expected, just displaying the content and hoping the browser will show it isn't simple.

This is because our content is stored in a string format rather than an HTML format, which can make the process slightly more complex. To successfully display the react-draft-wysiwyg blog content, we will utilize the dompurify package.

I intentionally added a few bugs in this code. I encourage you to find those bugs, raise an issue in my GitHub repo, and create a Pull Request to resolve them.

Installing dompurify package

Open up your VSCode terminal and navigate to your project directory, and use npm to install the dompurify package:

npm i dompurify

DOMPurify is a valuable library designed to safeguard web applications against Cross-Site Scripting (XSS) attacks. It achieves this by meticulously sanitizing and cleansing potentially hazardous HTML and DOM elements, ensuring a secure browsing experience for users.

Cross-site scripting (XSS) attacks occur when an attacker injects malicious code, often in the form of JavaScript, into a website's content. When other users view this content, the injected code can execute in their browsers, leading to various security vulnerabilities.

It takes a piece of HTML content as input and cleans it by removing any potentially harmful elements or attributes. This process ensures that only safe and allowed elements are retained.

In a React application, DOMPurify is frequently utilized alongside the dangerouslySetInnerHTML property to securely render user-generated or dynamic HTML content. This approach is particularly beneficial when displaying rich text, blog entries, comments, or any content that might include HTML elements.

The process effectively eliminates potentially harmful elements or attributes, ensuring that only safe and permitted components are retained.

Here's a basic example of how DOMPurify can be used in a React component:

import React from 'react';
import DOMPurify from 'dompurify';

function cleanHTML({ htmlContent }) {
  const sanitizedHtml = DOMPurify.sanitize(htmlContent);

  return <div dangerouslySetInnerHTML={{ __html: sanitizedHtml }} />;
}

export default cleanHTML;

In this example, the cleanHTML component takes an htmlContent prop containing the potentially unsafe HTML content. DOMPurify is used to sanitize the content, and then the sanitized HTML is rendered using the dangerouslySetInnerHTML prop.

By utilizing DOMPurify, we can guarantee that user-generated content containing HTML is displayed in a secure and controlled way, minimizing the risk of XSS attacks.

Creating a View Blog Page

import {  Container } from "react-bootstrap";
import PropTypes from "prop-types";
import { useState, useEffect } from "react";
import { useSearchParams, useNavigate } from "react-router-dom";
import DOMPurify from 'dompurify';


function ViewBlog({blogList}) {

  const [blogTitle, setBlogTitle] = useState("");
  const [convertedBlogContent, setConvertedBlogContent] = useState(null);


  //Route hooks
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();

   //UseEffect
  useEffect(() => {

  const blogId = searchParams.get("blogID");

if(blogList.length == 0){
  navigate({pathname:'/'});
}
  if(blogId && blogList.length != 0){


   setBlogTitle(blogList[blogId].title);
setConvertedBlogContent(blogList[blogId].content);
  }

   }, [blogList]); 

   function createMarkup(html) {
    return {
      __html: DOMPurify.sanitize(html)
    }
  }


  return  <div className="main-content">
      <Container>

        <section id="bloglist-title-section">
          <div className="bloglist-title">
            <h2>{blogTitle}</h2>
            <i className="fa fa-file-text-o" aria-hidden="true"></i>
          </div>
        </section>
        <section id="bloglist-section">
         <div       className="preview"
        dangerouslySetInnerHTML={createMarkup(convertedBlogContent)}>
         </div>
        </section>
      </Container>
    </div>;
}

ViewBlog.propTypes = {
  blogList: PropTypes.any,
};

export default ViewBlog;

This code defines a React component named ViewBlog that is used to display the content of a specific blog post. It uses the react-bootstrap library for styling and layout. The component takes a prop named blogList, which presumably contains an array of blog data.

  1. State Variables: The component has two state variables: blogTitle and convertedBlogContent. These states will hold the title and content of the selected blog post.

  2. Route Hooks: It uses useSearchParams and useNavigate from react-router-dom to access the query parameters from the URL and to navigate between pages.

  3. Effect (useEffect): When the component mounts or the blogList changes, the useEffect hook is triggered. It retrieves the blogID from the query parameters. If blogList is empty or no blogID is provided, it navigates the user back to the homepage which is blog list page. If both conditions are met, it sets the blogTitle and convertedBlogContent states based on the corresponding blog data from the blogList.

  4. DOMPurify: The function createMarkup takes HTML content as input, and using the DOMPurify library, it sanitizes and creates a markup object to render the content as HTML safely.

  5. Rendering: The JSX in the return statement renders the blog's title and content in a container. The title is displayed within a header element, and the content is rendered using the dangerouslySetInnerHTML prop to insert sanitized HTML content.

  6. PropTypes: The propTypes property is used to specify the expected type of the blogList prop.

In summary, this component takes the blog data, extracts the relevant blog post using query parameters, and displays its title and content in a safe manner using sanitized HTML.

You can get all this code from GitHub repository

Run your APP

Simply run the following command in your terminal:

npm run dev

Now, give yourself a pat on the back, as you've just implemented a method to display safe HTML content that protects us from Cross-site Scripting (XSS) attacks in our React app.

So, that concludes this blog post.

What's Next?

Oh, what an exciting journey we've had so far, exploring the basics of React and discovering some incredibly handy packages that can be used in any React app! But wait, there's more!

In our next blog post, we'll dive into deploying our React app on Vercel. And guess what? You can deploy as many React projects as you want for free! I can't wait to guide you through the process of deploying your React app from GitHub to Vercel, step by step. Stay tuned!

Conclusion

In conclusion, this article guided you through creating a blog view page in a React app, using the DOMPurify package to ensure the safe rendering of user-generated content.

By following this tutorial, you have gained valuable knowledge on handling and displaying HTML content securely, protecting your application from XSS attacks. Stay tuned for the next part of the series, where we'll explore deploying your React app on Vercel.

Follow me on Twitter or Linkedin I share about Cloud, System Design, Code, and many more tech stuff ๐Ÿ˜Š

Resources

Did you find this article valuable?

Support Pradhuman Blog by becoming a sponsor. Any amount is appreciated!

ย