3D Printing/Modeling, Woodworking, Coding and generally making stuff

Safely Decoding HTML Entities in React

Table of Contents

Why use he when I hate adding dependencies?

  • Zero Dependencies: he is a standalone library with no dependencies, ensuring a lightweight addition to your project.
  • Trusted by Millions: With nearly 20 million downloads, he has proven its reliability and effectiveness in the developer community.
  • Comprehensive & Secure: he supports decoding of all HTML entities, , enhancing content readability while helping mitigate XSS vulnerabilities without the risk associated with dangerouslySetInnerHTML.

Integrating he into Your React Application

Installation

First, add he to your project:

npm install he

Practical Usage Examples

Rendering User-Generated Comments

import React from 'react';
import he from 'he';

function Comment({ text }) {
  return <div className="comment">{he.decode(text)}</div>;
}

This snippet showcases how effortlessly he decodes user-generated comments, ensuring special characters are correctly displayed.

Displaying Content from Third-Party APIs

import React from 'react';
import he from 'he';

function Article({ articleContent }) {
  return <article>{he.decode(articleContent)}</article>;
}

Here, he decodes HTML entities in articles fetched from an external API, ensuring that special characters are rendered as intended.

Enhancing Markdown Snippets for a Blog's Table of Contents

For blogs utilizing markdown, creating a table of contents often involves generating snippets that may contain HTML entities. Here's how he can be applied:

import React from 'react';
import he from 'he';

function TableOfContents({ posts }) {
  const extractSnippet = (content) => {
    const decodedContent = he.decode(content);
    return `${decodedContent.split(/\s+/).slice(0, 30).join(" ")}...`;
  };

  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>
          <a href={`#${post.id}`}>{post.title}</a> - {extractSnippet(post.content)}
        </li>
      ))}
    </ul>
  );
}

This example demonstrates how he facilitates creating readable, engaging snippets for a table of contents by accurately decoding HTML entities in markdown content.

Conclusion

For React developers and markdown content creators, the he library is small, uncomplicated and serves an important purpose. If you are working with user-generated content, third-party APIs, or markdown, I suggest you take a look.

March 12, 2024 (1mo ago)

code

#web#react#typescript